#!/usr/bin/env python3 """lhbox — the command line for LakehouseBox. Invoked as `lhbox`; the package on PyPI is `lakehousebox`. Configuration is `LHBOX_*` in the environment and `~/.config/lhbox/credentials.json` on disk (`$XDG_CONFIG_HOME/lhbox/` when that is set; `LHBOX_CREDENTIALS` names any other file; rebrand 2026-09-22, no compatibility layer: the service had no customers). Deliberate choices, all of them for the benefit of agents rather than humans: * **stdlib only.** No pip install, no virtualenv, no version conflicts. An agent that can run python3 can run this. * **JSON when piped, a table when it is a terminal.** An agent gets machine-readable output without having to know to ask; a human gets something readable. `--json` / `--human` override. * **Exit codes carry the error class**, so a script can branch without parsing anything, and the one decision a caller actually has to make — *retry, or change the request?* — is answerable from the code alone: 0 ok 1 invalid input the values you sent are wrong; fix them, never retry unchanged 2 limit or conflict a real quota or a real 409; stop and change the plan 3 auth key missing, wrong or revoked 4 not found no such project / catalog / namespace / table 5 server, unreachable or busy ours, the network's, or a 429 (busy, rate_limited): retry with backoff, after the retry_after_seconds the error names -- unless the error's `outcome` is "unknown": the request reached the server and may have completed, so check first (the remedy names the command); "not_sent" and "failed" are safe 6 usage error the command line itself is malformed; fix the command, never retry Codes 2 and 6 used to be the same code, which made 2 unbranchable: a blown quota and a typo in a flag are opposite decisions. Code 5 is never returned for a client mistake, because 5 is the one code that means "retry" and a retried client mistake loops forever. * **The typed error body goes to stderr verbatim.** It already names the limit, the current value and the remedy; reformatting it would only lose information. A 5xx answer to a mutation gains `outcome` and a check-first remedy (the server's own is kept as `server_remedy`). * **stdout is one JSON document, or nothing.** Piped or with --json, a success prints exactly one JSON value on stdout and a failure prints nothing there: its envelope goes to stderr, and every refusal -- a usage error included -- is an envelope too. Notes and progress are plain lines on stderr. `tests/test_output_contract.py` holds every command to it. * **`--idempotency-key` on every mutation**, because agents retry. Any string is accepted. * **`--column name:type` shorthand**, because hand-writing Iceberg schema JSON with correct field-ids is a reliable way for an agent to waste three turns. This wraps the same REST API a human or an agent could call with curl. It holds no logic of its own: if something is possible here and not over HTTP, that is a bug. Words (2026-09-20, docs/rename-plan.md): a person meets a CATALOG (an Iceberg catalog; organisation -> catalog -> namespace -> table). The CLI calls the API's catalog names (/v1/catalogs, catalog_id; the older `warehouse` names are aliases until docs/rename-plan.md §6 step 3), and the command group is `lhbox catalog` with `lhbox warehouse` as a hidden alias of the same parser, every `--catalog` flag has a `--warehouse` twin on the same dest, and echoed API fields keep their names. """ import argparse import base64 import datetime import errno import glob import hashlib import hmac import http.client import json import platform as pyplatform import re import shlex import shutil import signal import socket import subprocess import tempfile import threading import time import os import sys import urllib.error import urllib.parse import urllib.request import uuid import webbrowser # The one place the version lives. platform/cli/pyproject.toml reads it from here (hatch "regex" # version source), the installer at lakehousebox.com/install.sh prints it, docs/cli-distribution.md says # how a release is cut. Every change to this file bumps it: `./al check` (scripts/cli_version_check.sh) fails a branch # whose lhbox differs from master's under the same version. `--version` adds the build (the file's own SHA-256), so # two copies can be told apart even so. __version__ = "0.6.212" def _env(name, default=None): """`LHBOX_` from the environment, else the default.""" v = os.environ.get("LHBOX_" + name) return default if v is None else v MANAGED_URL = "https://api.lakehousebox.com" DEFAULT_URL = _env("URL", MANAGED_URL) SITE_URL = "https://lakehousebox.com" # the website (docs, legal); api., catalog., s3. and mcp. live under the same domain def site_url(args): """The website behind the API a command talks to: lakehousebox.com for the service (docs/rename-plan.md), the API's own host without its `api.` label for a self-hosted or local stack.""" url = (getattr(args, "url", None) or DEFAULT_URL).rstrip("/") if url.endswith("lakehousebox.com"): return SITE_URL return url.replace("://api.", "://", 1) EXIT_OK, EXIT_ERROR, EXIT_LIMIT, EXIT_AUTH, EXIT_NOTFOUND, EXIT_SERVER = 0, 1, 2, 3, 4, 5 EXIT_USAGE = 6 def exit_code_for(status, error_code=""): """HTTP status (plus the server's typed error code) -> exit code. The ONE mapping, used by every request path -- authenticated, signup/recover, login and the bearer exchange -- so the contract in the module docstring holds for `lhbox signup` exactly as it does for `lhbox table get`. The 2026-09-20 review found the unauthenticated paths answering 1 for a 404 and a 500.""" if status in (401, 403): return EXIT_AUTH if status == 404: return EXIT_NOTFOUND if status == 409 or error_code == "limit_exceeded": return EXIT_LIMIT if status >= 500 or status in (429, 499): # 499 (the edge closed a connection the API never answered) is a retry like a 5xx. 429 (busy, rate_limited) says "wait retry_after_seconds, then send it again": the retry code, never 1, # which tells a script not to retry (the review of #423: the query routes answer 429 far more often now) return EXIT_SERVER return EXIT_ERROR # The output mode, decided once by run() -- from argv before parsing, so a usage error is answered in it too, then from # the parsed flags. None (a test calling a cmd_* directly): JSON when stdout is not a terminal, as _want_json() decides. _OUTPUT_JSON = [None] _EXIT_CODE_NAMES = {EXIT_ERROR: "invalid_input", EXIT_LIMIT: "conflict", EXIT_AUTH: "auth", EXIT_NOTFOUND: "not_found", EXIT_SERVER: "unavailable", EXIT_USAGE: "usage_error"} def _json_mode(): return _OUTPUT_JSON[0] if _OUTPUT_JSON[0] is not None else not sys.stdout.isatty() _SILENT = threading.local() # .on: this thread's refusals raise SystemExit without printing (CatalogTokenBroker's renewals) def die(msg, code=EXIT_ERROR): """A refusal: plain words for a person at a terminal; for a machine (piped, --json) the same words in the error envelope on stderr, its code named after the exit class -- 89 refusals used to be text a script had to regex (docs/proposals/cli-consistency.md, topic 2).""" if getattr(_SILENT, "on", False): raise SystemExit(code) if _json_mode(): die_json(_EXIT_CODE_NAMES.get(code, "error"), msg, code) print(msg, file=sys.stderr) sys.exit(code) def die_json(code_name, message, exit_code=EXIT_USAGE, **detail): """A JSON interface must answer JSON even when the caller's file is missing or unparseable. Two probes used to come back as raw Python tracebacks here: unparseable for an agent, and they printed our absolute source paths and line numbers at a consumer. """ body = {"error": {"code": code_name, "message": message, **detail}} if getattr(_SILENT, "on", False): _SILENT.envelope = body # what it would have said: a --wait that gives up says it then (#2638) raise SystemExit(exit_code) _note_outdated(body["error"]) print(json.dumps(body, indent=2), file=sys.stderr) # inside `with _quiet():` an envelope printed here is final (the network, not an HTTP answer the caller handles): # _Fatal passes the handlers that catch a refusal, so no fallback runs after it and prints a second one raise (_Fatal if _QUIET[0] else SystemExit)(exit_code) def _shown_path(path): """A path as the CLI prints it: the home as `~`, never expanded (docs are generated from --help).""" home = os.path.expanduser("~").rstrip(os.sep) return "~" + path[len(home):] if home and (path == home or path.startswith(home + os.sep)) else path def _cred_file(): """Where the credentials file is, one rule for every command that reads or writes it (#1878): LHBOX_CREDENTIALS (made absolute when it is relative, so a later save in another directory still finds it, #2086), else $XDG_CONFIG_HOME/lhbox/credentials.json when XDG_CONFIG_HOME is an absolute path (the XDG spec ignores a relative one), else ~/.config/lhbox/credentials.json. -> (path, shown, source).""" named = _env("CREDENTIALS") if named: path = os.path.abspath(os.path.expanduser(named)) return path, named if os.path.isabs(os.path.expanduser(named)) else _shown_path(path), "LHBOX_CREDENTIALS" xdg = os.environ.get("XDG_CONFIG_HOME") or "" if os.path.isabs(xdg): path = os.path.join(xdg, "lhbox", "credentials.json") return path, _shown_path(path), "XDG_CONFIG_HOME" return os.path.expanduser(DEFAULT_CRED_FILE), DEFAULT_CRED_FILE, "default" DEFAULT_CRED_FILE = "~/.config/lhbox/credentials.json" CRED_FILE, CRED_FILE_SHOWN, CRED_FILE_SOURCE = _cred_file() CRED_FILE_EXPLICIT = _env("CREDENTIALS") is not None # LHBOX_CREDENTIALS names the file: that file alone, empty when it does not exist yet PROFILE_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$") DEFAULT_PROFILE = "default" _RESERVED = ("active", "profiles") # top-level keys of the credentials file that are not an API URL _PROFILE = [None] # --profile of the running command (set by run()); None: LHBOX_PROFILE, then the file class CredentialsUnreadable(OSError): """The credentials file exists but cannot be read or does not parse (#2573). A writer that read it as empty would replace it whole with its one entry, dropping every other saved login while their keys stay live: writers refuse.""" def remedy(self): return "repair or move %s (it may hold other saved logins)" % CRED_FILE_SHOWN def _read_file(strict=False): """The credentials file as a dict; {} when it does not exist yet. One that exists but cannot be read or parsed is {} to a reader, and raises CredentialsUnreadable when strict (every caller that writes the file back).""" try: with open(CRED_FILE) as fh: text = fh.read() # an empty file (a `touch`ed one to bind-mount, or one cut short) holds no login to protect raw = json.loads(text) if text.strip() else {} except (FileNotFoundError, NotADirectoryError): return {} # no file there (none can be, under a path that is not a folder): nothing to keep except OSError as exc: if strict: raise CredentialsUnreadable(exc.errno or errno.EIO, "%s cannot be read (%s)" % (CRED_FILE_SHOWN, exc.strerror or exc)) from exc return {} except ValueError as exc: if strict: raise CredentialsUnreadable(errno.EINVAL, "%s does not parse (%s)" % (CRED_FILE_SHOWN, exc)) from exc return {} if not isinstance(raw, dict): if strict: raise CredentialsUnreadable(errno.EINVAL, "%s does not hold a JSON object" % CRED_FILE_SHOWN) return {} return raw def _write_json_0600(path, obj): """Write a JSON file whole or not at all (#2499): a 0600 temp file beside it, fsync, then rename onto it, so a write that fails half-way (a full disk, a kill) leaves the previous file untouched. A symlink keeps its link (the rename lands on the file it points at). A file that cannot be renamed onto (a single bind-mounted file: EBUSY/EXDEV) is written in place, as before, once its whole content has been written out successfully.""" target = os.path.realpath(os.path.abspath(path)) folder = os.path.dirname(target) os.makedirs(folder, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix=".lhbox.", suffix=".tmp", dir=folder) # mkstemp creates it 0600 try: with os.fdopen(fd, "w") as fh: json.dump(obj, fh, indent=1) fh.flush() os.fsync(fh.fileno()) try: os.replace(tmp, target) tmp = None except OSError as e: if e.errno not in (errno.EBUSY, errno.EXDEV): raise out = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) os.fchmod(out, 0o600) with os.fdopen(out, "w") as fh: json.dump(obj, fh, indent=1) finally: if tmp: try: os.unlink(tmp) except OSError: pass def _write_file(raw): _write_json_0600(CRED_FILE, raw) _CRED_LOCK = {"depth": 0, "fd": None} class _cred_lock: """Every read-merge-write of the credentials file holds this (#2642): an exclusive flock on a sibling `credentials.json.lock`, so two lhbox processes saving logins at once (two profiles, two agents) each merge into the other's result instead of the rename that lands last dropping the other's login while its key stays live. Re-entrant within the process. Best effort where no lock can be had (no fcntl on Windows, a read-only folder holding a bind-mounted file): the write is then as before, whole but unserialised.""" def __enter__(self): _CRED_LOCK["depth"] += 1 if _CRED_LOCK["depth"] > 1: return self try: import fcntl target = os.path.realpath(os.path.abspath(CRED_FILE)) os.makedirs(os.path.dirname(target), exist_ok=True) fd = os.open(target + ".lock", os.O_RDWR | os.O_CREAT, 0o600) except (ImportError, OSError): return self try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: os.close(fd) return self _CRED_LOCK["fd"] = fd return self def __exit__(self, *exc): _CRED_LOCK["depth"] -= 1 if _CRED_LOCK["depth"] == 0 and _CRED_LOCK["fd"] is not None: fd, _CRED_LOCK["fd"] = _CRED_LOCK["fd"], None os.close(fd) # closing the only descriptor releases the flock return False def _profiles_of(raw): """{name: {api_url: entry}}: the `default` profile is the URL-keyed entries at the top of the file (what every login before profiles wrote, so it needs no migration); the named ones sit under `profiles`.""" out = {name: dict(m) for name, m in (raw.get("profiles") or {}).items() if isinstance(m, dict)} flat = {k: v for k, v in raw.items() if k not in _RESERVED} if flat or DEFAULT_PROFILE not in out: out[DEFAULT_PROFILE] = flat return out def _raw_of(profiles, active): raw = dict(profiles.get(DEFAULT_PROFILE) or {}) named = {n: m for n, m in profiles.items() if n != DEFAULT_PROFILE and m} if named: raw["profiles"] = named if active and active != DEFAULT_PROFILE: raw["active"] = active return raw def active_profile(strict=True): """The profile in force: --profile, else LHBOX_PROFILE, else the one `lhbox profile use` chose, else `default`. A bad name given as a flag or in the environment is refused (strict); a bad `active` in the file is ignored, and strict=False (error paths, `profile` commands) never refuses, so nothing that would repair it is blocked.""" asked = _PROFILE[0] or _env("PROFILE") name = asked or _read_file().get("active") or DEFAULT_PROFILE if not PROFILE_RE.match(str(name)): if asked and strict: die_json("invalid_profile", "profile name %r is not a lowercase word (a-z, 0-9, - and _; at most 32)" % name, EXIT_ERROR, remedy="use a name like garden or acme2") return DEFAULT_PROFILE return name def remembered_url(): """The server this machine logged in to, when no --url or LHBOX_URL says one: the active profile's saved login, if it holds exactly one API URL. Someone who ran `LHBOX_URL=https://api. lhbox login` keeps talking to their install without the variable (the CLI used to fall back to the managed service, sending a self-hosted install's people to lakehousebox.com); a profile with logins on several servers keeps the managed default, as before.""" urls = [u for u in saved_credentials() if isinstance(u, str) and u.startswith(("https://", "http://"))] return urls[0].rstrip("/") if len(urls) == 1 else None def profile_explicit(): return bool(_PROFILE[0] or _env("PROFILE")) def saved_credentials(): """The active profile's {api_url: entry}.""" return dict(_profiles_of(_read_file()).get(active_profile()) or {}) def save_credentials(args, entry, drop_pending=False): """Merge one API-base-URL entry into the active profile of the credentials file, owner-read-only. The 0600 mode on os.open applies only when the file is CREATED; an existing file keeps whatever mode it has, so fchmod after open is what actually guarantees the permission. A `pending_device` (the resume token of `login --no-wait`) in the current entry survives a save that does not carry one -- `signup --save` used to overwrite it and `login --resume` then said nothing was pending. The completion and the expiry of that login pass drop_pending=True.""" with _cred_lock(): name = active_profile() # inside the lock: `lhbox profile use` may change the file's choice raw = _read_file(strict=True) profiles = _profiles_of(raw) creds = profiles.setdefault(name, {}) url = args.url.rstrip("/") previous = creds.get(url) or {} if not drop_pending and previous.get("pending_device") and "pending_device" not in entry: entry = dict(entry, pending_device=previous["pending_device"]) creds[url] = entry _write_file(_raw_of(profiles, raw.get("active"))) return CRED_FILE def _before_minting(args): """Everything that would refuse the save of a key, checked before the request that mints it: an unreadable credentials file (#2573) and a profile name the CLI refuses (#2640: `lhbox --profile Work signup --code C --save` created the account, spent the code and minted a key, then refused the name and lost the key).""" _read_file(strict=True) active_profile() def _revoke_unsaved(args, entry): """Revoke a key the API just minted that could not be saved, with that key itself (a token may revoke itself, #2085; a key its own id). Never prints, never exits: -> True when one revoke answered 2xx.""" key = entry.get("api_key") or "" if not key: return False # request_status would fall back to another saved key: never conn = entry.get("connection") or {} token_id, org = entry.get("token_id") or conn.get("token_id"), conn.get("org_id") parts = key.split("_") key_id = entry.get("key_id") or (parts[2] if len(parts) >= 4 and all(parts[:3]) else None) paths = [] if token_id and org: paths.append("/v1/orgs/%s/tokens/%s" % (urllib.parse.quote(org), urllib.parse.quote(token_id))) if key_id: paths.append("/v1/api-keys/%s" % urllib.parse.quote(key_id)) for path in paths: _SILENT.on = True # an unreachable API raises SystemExit here without printing try: status, _ = request_status(args, "DELETE", path, bearer=key) except (SystemExit, Exception): status = 0 finally: _SILENT.on = False if 200 <= status < 300: return True return False def _save_minted(args, entry, drop_pending=False, rerun="run the command again"): """save_credentials for a key the API has just minted (signup, login, new). When the file cannot be written the key is revoked with itself and NEVER shown (#2086: it used to be lost while still live; showing it instead would put a live key in an agent's transcript): the error names the path, why it failed, and the token to revoke by hand when the revoke failed too.""" try: return save_credentials(args, entry, drop_pending=drop_pending) except OSError as exc: unreadable = isinstance(exc, CredentialsUnreadable) reason = exc.strerror if unreadable else "%s: %s" % (type(exc).__name__, exc.strerror or exc) revoked = _revoke_unsaved(args, entry) conn = entry.get("connection") or {} detail = {"credentials_file": CRED_FILE_SHOWN, "key_revoked": revoked} if revoked: msg = ("The key was created but could not be saved: %s; it was revoked." % reason if unreadable else "The key was created but could not be saved to %s (%s); it was revoked." % (CRED_FILE_SHOWN, reason)) else: name = conn.get("name") or entry.get("token_id") or conn.get("token_id") if name: detail["token"] = name msg = ("The key was created but could not be saved to %s (%s), and it could not be revoked: revoke %s on " "the account page (Connections)." % (CRED_FILE_SHOWN, reason, "the connection %s" % name if name else "it")) fix = exc.remedy() if unreadable else "fix the path (LHBOX_CREDENTIALS / XDG_CONFIG_HOME)" die_json("credentials_not_saved", msg, EXIT_ERROR, remedy="%s and %s" % (fix, rerun), **detail) def _api_key_or_none(args): """The key api_key() would use (--api-key, LHBOX_API_KEY, the saved login), or None.""" # `lhbox signup --save` / `lhbox login` wrote the saved one, keyed by API base URL return (getattr(args, "api_key", None) or _env("API_KEY") or (saved_credentials().get(args.url.rstrip("/")) or {}).get("api_key")) # --------------------------------------------------------------------------- a directory's token as the bearer # A SERVICE ACCOUNT (platform/docs/service-accounts.md) is an application of the organisation's own identity provider: it # holds no key of ours. Its bearer is the provider's client-credentials access token, got fresh by this process and kept # in memory only: from LHBOX_TOKEN_COMMAND (a command that prints one, e.g. a managed identity's `az account # get-access-token ... -o tsv`), or from the client credentials `lhbox login --client-credentials` saved (the secret # itself stays in the environment variable it names; the file never holds it, nor a token). _DIRECTORY_TOKEN = {} DIRECTORY_TOKEN_MARGIN = 60 # seconds before its exp a token is no longer reused def _jwt_exp(token): try: part = token.split(".")[1] return float(json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))).get("exp") or 0) except Exception: # noqa: BLE001 - not a JWT we can read: no reuse return 0.0 def _token_from_command(cmd): try: p = subprocess.run(shlex.split(cmd), capture_output=True, text=True, timeout=60) except (OSError, ValueError, subprocess.TimeoutExpired) as exc: die_json("token_command_failed", "LHBOX_TOKEN_COMMAND could not run: %s" % type(exc).__name__, EXIT_AUTH, remedy="Set LHBOX_TOKEN_COMMAND to a command that prints an access token of your identity provider.") token = (p.stdout or "").strip() if p.returncode != 0 or not token or any(c.isspace() for c in token): die_json("token_command_failed", "LHBOX_TOKEN_COMMAND exited %d without printing one access token." % p.returncode, EXIT_AUTH, stderr=(p.stderr or "").strip()[:300], remedy="Run the command yourself: it must print the token alone on stdout.") return token def _client_credentials_token(entry): var = entry.get("client_secret_env") or "" secret = os.environ.get(var) if var else None if not secret: die_json("missing_client_secret", "The client secret is read from the environment variable %s, which is not set." % (var or "(none named)"), EXIT_AUTH, remedy="export %s=... (the application's client secret), or run lhbox login --client-credentials again." % (var or "LHBOX_CLIENT_SECRET")) form = {"grant_type": "client_credentials", "scope": entry.get("scope") or ""} req = urllib.request.Request(entry["token_endpoint"], method="POST") req.add_header("Content-Type", "application/x-www-form-urlencoded") req.add_header("Accept", "application/json") if entry.get("client_auth") == "basic": pair = "%s:%s" % (urllib.parse.quote(entry["client_id"], safe=""), urllib.parse.quote(secret, safe="")) req.add_unredirected_header("Authorization", "Basic " + base64.b64encode(pair.encode()).decode()) else: form.update(client_id=entry["client_id"], client_secret=secret) req.data = urllib.parse.urlencode(form).encode() try: with urllib.request.urlopen(req, timeout=30) as r: out = json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): _die_timeout("POST", entry["token_endpoint"], 30, read=True) # a token request changes nothing (#2507) except urllib.error.HTTPError as e: try: body = json.loads(e.read().decode() or "{}") except ValueError: body = {} die_json("identity_provider_refused", "The identity provider refused the client credentials (HTTP %d %s)." % (e.code, body.get("error") or ""), EXIT_AUTH, error_description=str(body.get("error_description") or "")[:300], remedy="Check the client id, the secret, the scope, and that the application is enabled and holds its " "role or scope in the directory.") except urllib.error.URLError as e: _die_unreachable("POST", entry["token_endpoint"], e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url("POST", entry["token_endpoint"], e) token = out.get("access_token") if not token: die_json("identity_provider_refused", "The identity provider answered without an access token.", EXIT_AUTH) return token def _directory_entry(args): """The saved client-credentials login for this API, or None.""" entry = saved_credentials().get(args.url.rstrip("/")) or {} return entry if entry.get("kind") == "client_credentials" and entry.get("token_endpoint") else None def _directory_token(args): """The identity provider's access token this command sends as its bearer (LHBOX_TOKEN_COMMAND first, then a saved client-credentials login), or None when it has neither. Got once per process, again shortly before it expires.""" cmd = _env("TOKEN_COMMAND") entry = None if cmd else _directory_entry(args) if not cmd and not entry: return None if _DIRECTORY_TOKEN.get("token") and _DIRECTORY_TOKEN.get("exp", 0) - DIRECTORY_TOKEN_MARGIN > time.time(): return _DIRECTORY_TOKEN["token"] token = _token_from_command(cmd) if cmd else _client_credentials_token(entry) _DIRECTORY_TOKEN.update(token=token, exp=_jwt_exp(token) or time.time() + 300) return token VENDED_ONLY_REMEDY = ("Read with `lhbox query` (it runs on LakehouseBox's side); for a write, ask for a short-lived " "session on one table: POST /v1/credentials {catalog, namespace, name} (`lhbox credentials`). An " "engine recipe with the catalog's own key pair needs a person's API key.") def _require_static_recipe(rec, command): """A recipe without the catalog's key pair (credentials: vended_only -- a service account's or an MCP connection's, platform/docs/service-accounts.md) cannot drive `command`: one envelope saying what does work (review of #1450, 4).""" if isinstance(rec, dict) and rec.get("credentials") == "vended_only": die_json("vended_only", "This identity gets no static catalog key (a service account or an application connection), " "and `lhbox %s` needs one." % command, EXIT_AUTH, catalog=rec.get("warehouse_id"), level=rec.get("level"), remedy=VENDED_ONLY_REMEDY) return rec def _bearer(args): """What a request sends: an API key (--api-key, LHBOX_API_KEY, the saved login), else a directory's token (a service account), else the "No API key" refusal.""" return _api_key_or_none(args) or _directory_token(args) or api_key(args) def _xdg_moved_note(): """XDG_CONFIG_HOME moved the credentials file (#1878): a login saved before that, in the default file, is not read. Said where a missing key is reported, so nobody thinks it was lost; '' otherwise.""" if CRED_FILE_SOURCE != "XDG_CONFIG_HOME" or os.path.exists(CRED_FILE): return "" if not os.path.exists(os.path.expanduser(DEFAULT_CRED_FILE)): return "" return (" XDG_CONFIG_HOME is set, so the credentials file is %s; a login saved in %s is not read (run `lhbox " "login` for this one, or unset XDG_CONFIG_HOME, or set LHBOX_CREDENTIALS=%s)." % (CRED_FILE_SHOWN, DEFAULT_CRED_FILE, DEFAULT_CRED_FILE)) def api_key(args): key = _api_key_or_none(args) if not key: die("No API key. Run `lhbox login` (connects this machine to your catalog; you approve it in the " "browser), or `lhbox signup --email you@example.com --save`, or set LHBOX_API_KEY, or pass --api-key. " "No account and no person at hand: `lhbox new` makes a catalog you can write now; a person keeps it later " "(`lhbox claim`)." + _xdg_moved_note(), EXIT_AUTH) return key def key_source(args): """Where the key this command uses came from, never the key: `--api-key`, `LHBOX_API_KEY`, or `credentials file` (the order api_key() looks). A CLI and an MCP server can hold different keys of different organisations (2026-09-28, item 4); saying which one answered is what tells them apart.""" if getattr(args, "api_key", None): return "--api-key" if _env("API_KEY"): return "LHBOX_API_KEY" if not _api_key_or_none(args): if _env("TOKEN_COMMAND"): return "LHBOX_TOKEN_COMMAND (a service account's directory token)" if _directory_entry(args): return "client credentials (a service account's directory token)" name = active_profile() return "credentials file" if name == DEFAULT_PROFILE else "credentials file, profile %s" % name KEY_SWITCH_HINT = ("another account or organisation beside this one: lhbox --profile login, then lhbox profile use " " to switch (lhbox login --new replaces this profile's key instead); for one command: set " "LHBOX_API_KEY or pass --api-key") SLOW_ADMIN_TIMEOUT = 300 # catalog create / rotate / delete / measure: many IAM writes at the store, ~90 s measured on a busy host PROGRESS_INTERVAL = 10 # seconds between "still working" lines on stderr while a person waits on one of them PROVISION_POLL_INTERVAL = 5 # seconds between GET /v1/catalogs/{id} polls after a 202 provisioning answer def _is_timeout(exc): """A read timeout (http.client raises TimeoutError itself) or a connect/handshake timeout (urllib wraps it in URLError).""" if isinstance(exc, (TimeoutError, socket.timeout)): return True reason = getattr(exc, "reason", None) return isinstance(reason, (TimeoutError, socket.timeout)) or "timed out" in str(reason or "").lower() def _die_timeout(method, path, timeout, sent=True, idempotency_key=None, idempotent=None, read=None): """A timeout is not a bug and not a plain failure: the server may well have finished the work (catalog create and rotate did, 2026-09-21, while the CLI said "This is a bug… re-run" and a re-run would have made duplicates). Exit 5 (the retry code) with a remedy that says to look first. sent=False: the connection itself timed out (urllib wraps that in URLError), so nothing reached the server. read=True: a POST that changes nothing although its route is not one of ours (an identity provider's token endpoint, #2507).""" if not sent: _die_unreachable(method, path, "the connection timed out after %d s" % timeout) if read is None: read = _is_read(method, path) die_json("timeout", "%s %s did not answer within %d s. The request may still have completed on the server." % (method, path, timeout), EXIT_SERVER, method=method, path=path, timeout_seconds=timeout, outcome="failed" if read else "unknown", remedy=_retry_remedy(method, path, idempotency_key, idempotent, read)) # ---------------------------------------------------------------- what a failed request did (exit 5's `outcome`) # Exit 5 means "retry", and for a mutation that is only true when the request did nothing. The envelope says which: # not_sent nothing reached the server (connection refused, DNS, a connect timeout): retry with backoff # failed the server answered and did nothing, or it was a read: retry with backoff # unknown the request reached the server and the answer was lost or was a 5xx: it may have completed, so the remedy # names the command that shows whether it did (a rotate that completed and is re-run rotates twice) _READ_METHODS = ("GET", "HEAD") # POST routes that change nothing a retry could duplicate: a query, a vended short-lived credential, a token, a storage # measurement, a sink's dry run (high review of this change, finding 1), a scheduled-SQL preview (#2502) _READ_POSTS = ("/v1/query", "/v1/credentials", "/v1/tokens", "/v1/connection", "/v1/sql/preview") _READ_POST_SUFFIXES = ("/measure", "/test") # the server's 503s that refuse BEFORE doing anything (control_plane: ALError(503, …)); storage_unavailable is not one: # it is any transport error to the store, a read timeout after a commit included (finding 3) _REFUSED_BEFORE_WORK = {"provisioning", "storage_not_ready", "query_unavailable", "index_unavailable", "mapping_unavailable", "mfa_unavailable", "public_reader_unavailable", "temporarily_unavailable"} def _is_read(method, path): """Can re-sending this request change anything? GET/HEAD never; the read-only POST routes neither.""" p = (path or "").split("?")[0] return method.upper() in _READ_METHODS or (method.upper() == "POST" and (p in _READ_POSTS or p.endswith(_READ_POST_SUFFIXES))) # the routes whose create honours an Idempotency-Key (control_plane: idempotent() on POST /v1/tables, /v1/projects, # /v1/warehouses): re-sending with the same key answers the first result instead of creating twice _IDEMPOTENT_CREATES = ("/v1/tables", "/v1/projects", "/v1/catalogs", "/v1/warehouses") def _check_hint(path): """The command that shows whether a mutation on `path` took effect.""" p = (path or "").split("?")[0] if p.startswith(("/v1/catalogs", "/v1/warehouses")): if "/uploaders" in p: return "lhbox catalog uploader list " if "/grants" in p: return "lhbox catalog grants " if "/lifecycle" in p: return "lhbox catalog lifecycle get " if "/agents-md" in p: return "lhbox catalog agents-md " return "lhbox catalog list (or lhbox catalog get )" if re.match(r"^/v1/sinks/[^/]+(/|$)", p): # the list row shows no runs, dedupe or device-token state (#2503): a run shows in `sink runs`, the rest in `sink get` return "lhbox sink runs " if p.endswith("/run") else "lhbox sink get " for prefix, cmd in (("/v1/tables", "lhbox table get . --catalog "), ("/v1/table", "lhbox table get .
--catalog "), ("/v1/namespace", "lhbox namespace list --catalog "), ("/v1/sinks", "lhbox sink list"), ("/v1/indexes", "lhbox index list"), ("/v1/api-keys", "lhbox api-key list"), ("/v1/projects", "lhbox project list"), ("/v1/me", "lhbox whoami"), ("/v1/terms", "lhbox terms")): if p.startswith(prefix): return cmd m = re.match(r"^/v1/orgs/([^/]+)(/[^/]+(?:/tokens)?)?", p) if m and m.group(1) != "invitations": # the org is the path's: a check without --org fails as written for a person in two organisations (#2989) org, sub = " --org " + urllib.parse.unquote(m.group(1)), m.group(2) or "" for route, cmd in (("/tokens", "lhbox token list"), ("/scim/tokens", "lhbox org scim-token list"), ("/service-accounts", "lhbox org service-account list"), ("/group-rules", "lhbox org group-rules list"), ("/policy", "lhbox org policy")): if sub == route: return cmd + org if sub in ("/members", "/invitations"): return "lhbox org members" + org return "lhbox org list" if p.startswith("/v1/orgs/"): return "lhbox org list" if p.startswith("/v1/artifacts"): # a publish sent twice is a second page, or a second version return "lhbox artifact ls" # hosted agents, integrations (#2720): an agent's run and talk are paid, so a blind re-run can pay twice m = re.match(r"^/v1/(agents|integrations)(?:/([^/]+))?(/.*)?$", p) if m: kind, ref, tail = m.group(1), urllib.parse.unquote(m.group(2) or ""), m.group(3) or "" if kind == "agents": if not ref: return "lhbox agent list" if tail == "/run": return "lhbox agent runs %s" % ref if tail == "/talk": return "lhbox agent talk %s (with no message it lists the latest exchanges)" % ref return "lhbox agent show %s" % ref return "lhbox integration show %s" % ref if ref else "lhbox integration list" return "the matching `lhbox … list` or `get`" def _retry_remedy(method, path, idempotency_key=None, idempotent=None, read=None): """What to do after a failure whose outcome is unknown: check, then re-run -- or re-send with the same key where the server answers a repeated key with the first result (`idempotent`, by default the creates that honour one).""" if _is_read(method, path) if read is None else read: return "A read changes nothing: safe to retry with backoff." p = (path or "").split("?")[0] if idempotent is None: idempotent = method.upper() == "POST" and p in _IDEMPOTENT_CREATES if idempotent and idempotency_key: # the exact flag: `sink send` makes a fresh batch id per run unless given one (finding 5) flag = "--batch-id" if p.startswith("/v1/sinks/") else "--idempotency-key" return ("The request may have completed. Re-run it with %s %s (the same key): the server answers the first result " "instead of doing it twice; a re-run without it could do it twice." % (flag, idempotency_key)) if method.upper() == "POST" and p in _SESSION_REMEDIES: return _SESSION_REMEDIES[p] return ("The request reached the server and may have completed. Check before re-running: %s. Re-run only if it did " "not take effect." % _check_hint(path)) # the sign-in POSTs, whose lost answer leaves no key saved to check with (#2643): what to do instead, as a command _SESSION_REMEDIES = { "/v1/agent/identity": "The request may have made a catalog, but no key was saved, so nobody can use it (it is deleted " "unclaimed when its time runs out). Run `lhbox new` again.", "/v1/agent/identity/claim": "No claim code was saved; a claim whose answer was lost expires unused. Run `lhbox claim` " "again.", "/v1/signup/verify": "The account may have been created, but no key was saved. Run `lhbox login` to sign in to it; if " "there is no such account, start again with `lhbox signup --email
` (the code is spent).", "/v1/auth/device/token": "A login started with --no-wait: run `lhbox login --resume` again (a claim: `lhbox claim " "--resume`). Otherwise, or when it says nothing is pending or the code was used or expired, " "run `lhbox login` (or `lhbox claim`) again.", "/v1/auth/cli/token": "No key was saved. Run `lhbox login` again.", "/v1/onboard": "The key is saved. `lhbox catalog list` shows whether the catalog was made; if not, make one with " "`lhbox catalog create `.", } def _die_unreachable(method, url, reason): """Nothing reached the server: a connection refused, a name that does not resolve, a connect timeout.""" die_json("unreachable", "Cannot reach %s: %s" % (url, reason), EXIT_SERVER, method=method, outcome="not_sent", remedy="Nothing reached the server. Check --url / LHBOX_URL and the network; safe to retry with backoff.") # after the request was sent: http.client raises these raw (urllib wraps only the SENDING in URLError), and they used to # reach main()'s backstop as "unexpected RemoteDisconnected ... a bug in lhbox, re-run" -- exit 1 saying re-run, for a # request that may have completed (docs/proposals/cli-consistency.md, the hang-up probe) _LOST_ANSWER = (http.client.HTTPException, ConnectionError) def _die_lost_or_bad_url(method, path, exc, idempotency_key=None, idempotent=None): """http.client.InvalidURL (a non-numeric port in --url, a control character in a path) is raised outside urllib's URLError too, and it is the caller's mistake: exit 6, never the retry code (high review, finding 2).""" if isinstance(exc, http.client.InvalidURL): die_json("invalid_url", "The URL is malformed: %s" % exc, EXIT_USAGE, remedy="Fix --url / LHBOX_URL (scheme://host[:port]) or the name in the command; a retry fails the same way.") _die_lost(method, path, exc, idempotency_key, idempotent) def _die_lost(method, path, exc, idempotency_key=None, idempotent=None): """The request was sent and the connection ended before a whole answer came back.""" read = _is_read(method, path) die_json("connection_lost", "%s %s: the connection closed before the server's answer arrived (%s)." % (method, (path or "").split("?")[0], type(exc).__name__), EXIT_SERVER, method=method, path=(path or "").split("?")[0], outcome="failed" if read else "unknown", remedy=_retry_remedy(method, path, idempotency_key, idempotent)) def _die_interrupted(method, path, idempotency_key=None): """Ctrl-C while a request was on its way or the server worked on it (#2022): it may complete without us, so the retry class (5) with outcome unknown and the command that shows whether it did -- never exit 1 `invalid_input`, which tells a script its input was wrong (and a re-run rotate rotates twice).""" read = _is_read(method, path) die_json("interrupted", "%s %s was interrupted (Ctrl-C) after it was sent; the server may still complete it." % (method, (path or "").split("?")[0]), EXIT_SERVER, method=method, path=(path or "").split("?")[0], outcome="failed" if read else "unknown", remedy=_retry_remedy(method, path, idempotency_key)) class _Fatal(SystemExit): """An envelope already printed inside `with _quiet():` (unreachable, connection lost, timeout): the command ends.""" class _Refused(SystemExit): """An HTTP error answer inside `with _quiet():` -- the caller handles it, so nothing is printed. A SystemExit, so code that catches SystemExit around request() (and the tests' fakes, which raise it) keeps working.""" def __init__(self, status, parsed, code): super().__init__(code) self.status, self.parsed = status, parsed _QUIET = [0] class _quiet: """Inside it, request()'s HTTP errors raise _Refused instead of printing the envelope and exiting: for the calls whose failure is handled (a fallback, an optional part of an answer). A caught failure used to print its envelope anyway: two JSON documents on stderr, or one before a successful answer (docs/proposals/cli-consistency.md).""" def __enter__(self): _QUIET[0] += 1 def __exit__(self, *exc): _QUIET[0] -= 1 return False _CURRENT_URL = [DEFAULT_URL] # the API base the running command talks to (set by run()), for hints that name its site def _fail(method, path, status, parsed, idempotency_key=None, idempotent=None): """An HTTP error answer: the server's typed error on stderr, then the exit code of its class. A 5xx or 429 gains `outcome`: failed for a read, a 429 (refused before any work) or an error saying `completed: false`; unknown for any other mutation, whose remedy then says how to check (the server's own remedy stays, as server_remedy).""" code = (parsed.get("error") or {}).get("code", "") if isinstance(parsed, dict) else "" err = parsed.get("error") if isinstance(parsed, dict) else None # the API's own hint for an old lhbox rides beside FastAPI's {"detail"} on the router's 404/405 (#1512): kept server_hint = parsed.get("cli_outdated") if isinstance(parsed, dict) and not isinstance(err, dict) else None if status == 404 and not isinstance(err, dict) and isinstance(parsed, dict) and parsed.get("detail") == "Not Found": # the router's own bare 404 (no typed envelope): a path this API no longer serves, which is what an old # lhbox sends -- not a wrong id (tenant feedback 2026-10-02, item 3) published = _newer_published(fetch=False) newer = " (%s is published)" % published if published else "" parsed = {"error": {"code": "endpoint_not_found", "message": "the API does not serve %s %s" % (method, path), "remedy": "this lhbox %s may be older than the API%s: run `%s`; if it is current, the id " "or name in the command is the likely cause" % (__version__, newer, _update_command())}} err = parsed["error"] if not isinstance(err, dict): detail = parsed.get("detail") if isinstance(parsed, dict) and isinstance(parsed.get("detail"), str) else None parsed = {"error": {"code": "http_%d" % status, "message": detail or str(parsed)[:500]}} err = parsed["error"] if isinstance(server_hint, dict): err.setdefault("cli_outdated", server_hint) if status == 499 and not str(err.get("message") or "").strip(): # the edge's answer when the connection closed before the API answered, with no body (#3128): say what it was err["message"] = ("the connection closed before LakehouseBox answered (HTTP 499 from the edge, no body): a timeout " "or a connection reset on the way. On a CI runner, an upload that hangs and then ends like this is " "usually a path-MTU black hole: run `sudo sysctl -w net.ipv4.tcp_mtu_probing=1` on the runner, then " "the command again") if profile_explicit() or active_profile(False) != DEFAULT_PROFILE: err.setdefault("profile", active_profile(False)) if code in ("warehouse_not_found", "catalog_not_found"): others = [r["profile"] for r in _profile_rows() if not r["active"]] if others: err.setdefault("other_profiles", others) err["remedy"] = ((err.get("remedy") or "") + " (profile %s was used; other saved logins: %s -- try --profile NAME)" % (active_profile(False), ", ".join(others))).strip() if (status >= 500 or status in (429, 499)) and "outcome" not in err: if (status == 429 or _is_read(method, path) or err.get("completed") is False or (status == 503 and err.get("code") in _REFUSED_BEFORE_WORK)): err["outcome"] = "failed" else: err["outcome"] = "unknown" if err.get("remedy"): err["server_remedy"] = err["remedy"] # no "re-send with the same key" here: a create that ANSWERED with an error released its key (control_plane # idempotent()'s abandon()), so a re-send runs it again; the key holds for a lost answer or a timeout only # (finding 6). A sink batch id is different: the batch is stored once, whatever the error. err["remedy"] = _retry_remedy(method, path, idempotency_key if idempotent else None, idempotent) if _QUIET[0]: raise _Refused(status, parsed, exit_code_for(status, code)) _note_outdated(err) print(json.dumps(parsed, indent=2), file=sys.stderr) sys.exit(exit_code_for(status, code)) def unauth_request(args, method, path, body, timeout=60): """Signup calls: no API key yet.""" url = args.url.rstrip("/") + path req = urllib.request.Request(url, data=json.dumps(body).encode(), method=method) req.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): _die_timeout(method, path, timeout) except urllib.error.HTTPError as e: payload = e.read().decode() try: err = json.loads(payload).get("error", {}) except ValueError: err = {"code": "http_%d" % e.code, "message": payload[:200]} if _json_mode(): # the envelope goes to stderr like every other error (it went to STDOUT here, with --json only) _fail(method, path, e.code, {"error": err}) print("error: %s: %s" % (err.get("code"), err.get("message")), file=sys.stderr) if err.get("remedy"): print(" -> %s" % err["remedy"], file=sys.stderr) sys.exit(exit_code_for(e.code, err.get("code", ""))) except urllib.error.URLError as e: _die_unreachable(method, url, e.reason) if not _is_timeout(e) else _die_timeout(method, path, timeout, sent=False) except _LOST_ANSWER as e: _die_lost_or_bad_url(method, path, e) def _ask(prompt): """input() with its prompt on stderr: input() writes the prompt to stdout, where a piped caller reads JSON.""" sys.stderr.write(prompt) sys.stderr.flush() return input("") def cmd_signup(args): """email -> code -> account + catalog + THIS machine's connection (its key, never the person's), in one sitting.""" if args.save: _before_minting(args) # before the account and its key are made (#2573, #2640, #2641) held = (_saved_connection(args) or {}).get("api_key") status = _key_status(args, held)[0] if held else 401 if status not in (401, 403): # the new account's key would replace this profile's login of another account, that key left live with nobody # holding it (#2641); `lhbox new` and `login --client-credentials` refuse the same way. A key the API refuses # (401/403) is dead: replacing it leaks nothing. Busy or unreachable (0, 429, 5xx) says nothing: refused too die_json("already_connected", "This profile (%s) already holds a login for %s; `signup --save` would replace " "it while its key still works." % (active_profile(False), args.url.rstrip("/")), EXIT_USAGE, remedy="Keep both: `lhbox --profile signup ... --save`; or replace it: `lhbox logout` (revokes " "the saved key), then run the signup again.") code = args.code if not code: # no code yet: ask for one. With a terminal, wait for it here; without one (an agent, a # script), stop after the request and say how to finish. body = {"email": args.email} if args.workspace: body["workspace"] = args.workspace for field in ("full_name", "organization", "handle"): if getattr(args, field, None): body["organization_name" if field == "organization" else field] = getattr(args, field) started = unauth_request(args, "POST", "/v1/signup/start", body) if started.get("waitlisted"): # launch-day admission (docs/launch-capacity.md): the deployment is onboarding in batches; nothing was # created and no code was sent. Not an error: the address is in line and will get an email if _want_json(args): print_json(started) else: print("%s\n(%s is on the waitlist; the email will carry a link to finish the account.)" % (started.get("message") or "You're on the waitlist.", args.email)) return if started.get("delivery") == "idp": # the identity provider mailed the account-setup link: there is no code to type here if _want_json(args): print_json(started) else: print(started.get("next") or "Check your email to finish setting up your account.") return where = ("your inbox" if started.get("delivery") == "email" else "the control-plane log (this deployment has no mail server)") if not sys.stdin.isatty(): if _want_json(args): started["next"] = "lhbox signup --email %s --code " % args.email print_json(started) else: print("A %d-digit code was sent to %s for %s (valid %d minutes). Finish with:\n" " lhbox signup --email %s --code %s" % (started.get("code_length", 6), where, args.email, started.get("expires_in", 600) // 60, args.email, " --save" if args.save else "")) return # a question to the person at the terminal: on stderr, so a piped stdout still gets one JSON document print("A %d-digit code was sent to %s for %s; it expires in %d minutes." % (started.get("code_length", 6), where, args.email, started.get("expires_in", 600) // 60), file=sys.stderr) code = _ask("Code: ").strip() if not args.accept_terms: if sys.stdin.isatty(): print("Creating an account means accepting the Terms of Service and Privacy Policy:\n" " %s\n %s" % (site_url(args) + "/legal/terms", site_url(args) + "/legal/privacy"), file=sys.stderr) ans = _ask("Accept? [y/N] ").strip().lower() if ans not in ("y", "yes"): die("Not accepted; no account created.", EXIT_USAGE) else: die("Pass --accept-terms to accept the Terms of Service (see /v1/signup/start .terms.url).", EXIT_USAGE) # the key that comes back is a connection of this machine (2026-10-01): named after it, as `lhbox login` names one hostname = socket.gethostname() out = unauth_request(args, "POST", "/v1/signup/verify", {"email": args.email, "code": code, "engine": args.engine, "accept_terms": True, "client": "cli", "hostname": hostname, "client_name": hostname}, timeout=300) show_key = getattr(args, "show_key", False) tok = out.get("token") or {} if args.save: pending = (_saved_connection(args) or {}).get("pending_device") entry = {"api_key": out["api_key"], "email": args.email, "warehouse_id": _cid(out)} if out.get("kind") == "token": # the entry `lhbox login` writes (_finish_connection), so a later login reuses it ("Still connected") entry.update({"key_id": out.get("key_id"), "kind": "token", "token_id": out.get("token_id"), "connection": {"token_id": tok.get("token_id"), "name": tok.get("name"), "org_id": tok.get("org_id"), "warehouses": [{"warehouse_id": _cid(w), "name": w.get("name"), "level": w.get("level")} for w in tok.get("warehouses") or []]}}) out["saved_to"] = _save_minted(args, entry, rerun="run `lhbox login` (the account exists)") if pending: # a `login --no-wait` is still waiting for its approval: kept next to the new key (2026-09-21 it was overwritten) out["pending_login"] = {"user_code": pending.get("user_code"), "verification_uri": pending.get("verification_uri"), "resume": "lhbox login --resume", "note": "kept in the credentials file; the person may still approve it"} print("note: a device login is still pending (code %s); it was kept -- `lhbox login --resume` finishes it, or ignore it and it expires." % pending.get("user_code"), file=sys.stderr) # the key is printed only when it is the caller's sole way to receive it (no --save) or on request # (--show-key): a saved key has no business in a terminal transcript an agent will read back hide_key = args.save and not show_key # the storage credential the recipe repeats (sql, blob_example_python, catalog_credential) is masked the same way the # uploader's secret is; `lhbox connect` fetches it whenever an engine needs it, --show-key prints it here conn = out.get("connection") or {} if not show_key: out = mask_secrets(out, [(conn.get(k) or {}).get("client_secret") for k in ("catalog_credential", "catalog_credential_ro")]) conn = out.get("connection") or {} if _want_json(args): print_json(_without_key(out) if hide_key else out) return print("Your catalog is ready.") if tok: print(" this machine: connected as %s (%s); the key is the connection's, not yours" % (tok.get("name"), ", ".join("%s on %s" % (w.get("level"), w.get("name")) for w in tok.get("warehouses") or []))) print(" catalog id: %s (warehouse_id in the API)" % _cid(out)) print(" catalog_uri: %s (storage %s)" % (conn.get("catalog_uri"), conn.get("warehouse"))) if hide_key: print(" api_key: saved to %s (not shown; --show-key prints it)" % CRED_FILE) else: print(" api_key: %s <- shown once%s" % (out["api_key"], "; saved to " + CRED_FILE if args.save else "")) if not show_key: print(" storage key: not shown (lhbox connect prints the recipe; --show-key prints it here)") if not args.save: print(" export LHBOX_API_KEY=%s" % out["api_key"]) print("Next: lhbox connect --engine duckdb (your only catalog needs no --catalog; lhbox catalog list names it)") if tok: print("Account page (organisation, catalogs, connections): set your password first at %s/app/forgot" % site_url(args)) def _without_key(out): """The same answer with the key replaced by its masked form (recognisable, unusable).""" shown = dict(out) if shown.get("api_key"): shown["api_key_masked"] = mask_key(shown.pop("api_key")) return shown SECRETS_MASKED_NOTE = ("the catalog credential's secret is shown as ******** (the key id is not secret): --show-secrets " "prints it (pipe it into the engine: `lhbox connect --show-secrets --human | duckdb`); `lhbox duckdb` " "attaches without showing it; the sample code reads the pair from the variables credential_env names") # a masked DuckDB recipe pasted as is would CREATE SECRET with ******** and fail later with a bare OAuth 401: its first # statement stops with the fix instead (DuckDB's error()); --show-secrets recipes carry no such line MASKED_SQL_GUARD = ("SELECT error('lhbox: this recipe''s secret is masked (********): run `lhbox connect --show-secrets " "--human | duckdb`, or `lhbox duckdb`');") def masked_recipe(out): """A connection recipe (or a rotate answer) with the secret of catalog_credential, catalog_credential_ro and an Edge reads credential masked everywhere it appears, marked secrets_masked with the note that says how to see it. Nothing to mask: unchanged.""" if not isinstance(out, dict): return out secrets = [(out.get(k) or {}).get("client_secret") for k in ("catalog_credential", "catalog_credential_ro")] # Edge reads: the edge credential's secret reads the whole catalog through the edge for its hour (high review of #1873) secrets.append((out.get("edge_reads") or {}).get("secret_access_key") if isinstance(out.get("edge_reads"), dict) else None) # ... and its capability, the catalog's address at the edge for the day: a holder reads what is cached (research/99) secrets.append((out.get("edge_reads") or {}).get("capability") if isinstance(out.get("edge_reads"), dict) else None) # ... and the files bucket's own edge credential and capability (research/100: the catalog's files through the CDN) files = (out.get("edge_reads") or {}).get("files") if isinstance(out.get("edge_reads"), dict) else None if isinstance(files, dict): secrets += [files.get("secret_access_key"), files.get("capability")] if not any(secrets): return out shown = mask_secrets(out, secrets) if shown.get("engine") == "duckdb" and shown.get("sql") and shown["sql"] != out.get("sql"): shown["sql"] = MASKED_SQL_GUARD + "\n" + shown["sql"] shown["secrets_masked"] = True shown["secrets_note"] = SECRETS_MASKED_NOTE return shown def mask_secrets(obj, secrets): """The same object with every occurrence of each secret replaced by ********, wherever it appears (a field, a recipe, a code sample). The one masking rule for storage secrets: the uploader's secret and the catalog credential use it.""" text = json.dumps(obj) for secret in secrets: if secret: text = text.replace(json.dumps(str(secret))[1:-1], "********") return json.loads(text) CATALOG_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,62}$") UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") def with_catalog_keys(obj): """JSON output says catalog as well as the API's warehouse (docs/rename-plan.md): every object with a `warehouse_id` gains `catalog_id`, every `warehouse_name` that IS a catalog name (matches ^[a-z][a-z0-9_]{0,62}$) gains `catalog_name`; a `warehouse_name` holding a bucket (`w-`, `acme--sales`) is left alone. The old keys stay: the harnesses read them.""" if isinstance(obj, list): return [with_catalog_keys(x) for x in obj] if not isinstance(obj, dict): return obj out = {} for k, v in obj.items(): out[k] = with_catalog_keys(v) if k == "warehouse_id" and v and "catalog_id" not in obj: out["catalog_id"] = v elif k == "warehouse_name" and "catalog_name" not in obj and isinstance(v, str) and CATALOG_NAME_RE.match(v): out["catalog_name"] = v return out def print_json(obj): """Every JSON answer on stdout goes through here: the catalog keys added, two-space indent.""" print(json.dumps(with_catalog_keys(obj), indent=2)) def _history_headers(args): """What a change made by this command says about itself in the object history (GET /v1/changes, `lhbox history`): why (--reason, or LHBOX_REASON), a link to where it was decided (--ref), and for `lhbox apply` the operation every change of that run shares. Percent-encoded: a header carries ASCII, a reason any text.""" out = {} reason = getattr(args, "reason", None) or os.environ.get("LHBOX_REASON") ref = getattr(args, "ref", None) or os.environ.get("LHBOX_REF") if reason: out["X-Lhbox-Reason"] = urllib.parse.quote(str(reason).strip()[:500], safe=" ,.:;!?()'/@#&=+-_") if ref: out["X-Lhbox-Ref"] = urllib.parse.quote(str(ref).strip()[:500], safe=":/?#[]@!$&'()*+,;=-._~%") if getattr(args, "_operation", None): out["X-Lhbox-Operation"] = args._operation out["X-Lhbox-Via"] = "apply" return out def request_status(args, method, path, body=None, idempotency_key=None, timeout=60, bearer=None, raw_body=None, content_type=None): """One authenticated call that does NOT exit on an HTTP error: (status, parsed body). `doctor` and `terms --accept` read a refusal out of the answer instead of dying on it; an unreachable API is still the network exit code, because nothing can be read out of that. `bearer` replaces the agent's API key on the wire (the operator key of `lhbox admin`); the default is the key api_key() resolves. `raw_body` sends bytes as they are with `content_type` (a device body for `sink test`) instead of a JSON body.""" url = args.url.rstrip("/") + path data = raw_body if raw_body is not None else (json.dumps(body).encode() if body is not None else None) req = urllib.request.Request(url, data=data, method=method) req.add_unredirected_header("Authorization", "Bearer " + (bearer or _bearer(args))) if data is not None: req.add_header("Content-Type", content_type if raw_body is not None and content_type else "application/json") if idempotency_key: req.add_header("Idempotency-Key", idempotency_key) for name, value in _history_headers(args).items(): req.add_header(name, value) try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read() return resp.status, (json.loads(raw) if raw else {}) except (TimeoutError, socket.timeout): _die_timeout(method, path.split("?")[0], timeout, idempotency_key=idempotency_key) except urllib.error.HTTPError as e: raw = e.read() try: parsed = json.loads(raw) except Exception: parsed = {"error": {"code": "http_%d" % e.code, "message": raw.decode(errors="replace")[:500]}} return e.code, parsed except urllib.error.URLError as e: if _is_timeout(e): _die_timeout(method, path.split("?")[0], timeout, sent=False) _die_unreachable(method, url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url(method, path, e, idempotency_key) def request(args, method, path, body=None, idempotency_key=None, timeout=60, bearer=None, raw_body=None, content_type=None): """One authenticated call. `timeout` is 60 s except for the few operations that drive many storage calls in one request (catalog create, rotate, delete, measure: identities, policies, buckets), which get SLOW_ADMIN_TIMEOUT.""" status, parsed = request_status(args, method, path, body, idempotency_key, timeout, bearer=bearer, raw_body=raw_body, content_type=content_type) if status >= 400: # The server's typed error is more useful than anything we could say about it. _fail(method, path, status, parsed, idempotency_key) return parsed def request_slow(args, method, path, body=None, idempotency_key=None, what="working"): """A slow admin call (catalog create / rotate / delete / measure), with the long timeout and, while a PERSON waits (not in JSON mode), a line on stderr every PROGRESS_INTERVAL seconds -- never a silent 90 s. The call runs in a thread so the ticker can print; a typed exit raised in it is re-raised here. Returns (status, body): the caller reads a 202 out of it.""" result = {} def go(): try: result["value"] = request_status(args, method, path, body, idempotency_key, SLOW_ADMIN_TIMEOUT) except BaseException as exc: # noqa: BLE001 - SystemExit from die() included, re-raised below result["exc"] = exc t = threading.Thread(target=go, daemon=True) t0 = time.time() t.start() talk = not _want_json(args) next_note = t0 + PROGRESS_INTERVAL try: while t.is_alive(): t.join(min(0.2, PROGRESS_INTERVAL)) if talk and t.is_alive() and time.time() >= next_note: print("%s… %d s; the store's identity writes are slow, this can take up to 2 minutes" % (what, int(time.time() - t0)), file=sys.stderr, flush=True) next_note = time.time() + PROGRESS_INTERVAL if "exc" in result: raise result["exc"] except KeyboardInterrupt: _die_interrupted(method, path, idempotency_key) status, parsed = result["value"] if status >= 400: _fail(method, path, status, parsed, idempotency_key) return status, parsed def _want_json(args): return args.json or (not args.human and not sys.stdout.isatty()) def emit(args, obj, columns=None, headers=None): """JSON when piped or asked for; a small table when a human is watching. `headers` maps a column key to the word a person reads over it (warehouse_id -> "catalog id"); JSON always keeps the API's names.""" if _want_json(args): print_json(obj) return rows = obj if isinstance(obj, list) else None if rows is None: for k, v in obj.items(): print("%-26s %s" % (_visible((headers or {}).get(k, k)), _visible(v if not isinstance(v, (dict, list)) else json.dumps(v), lines=True))) return _table(rows, columns, headers) _CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]") _CONTROL_CHARS_BUT_LINES = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") def _visible(v, lines=False): """A server-supplied value as a person's terminal shows it: C0/C1 control characters (escape sequences, BEL, CR) written as a visible \\xNN, never obeyed; newline and tab too unless `lines` (a recipe's SQL keeps its lines). A table's doc or name is another person's text (#2930).""" return (_CONTROL_CHARS_BUT_LINES if lines else _CONTROL_CHARS).sub(lambda m: "\\x%02x" % ord(m.group()), str(v)) def _table(rows, columns=None, headers=None): if not rows: print("(none)") return cols = columns or list(rows[0].keys()) label = {c: _visible((headers or {}).get(c, c)) for c in cols} cells = [{c: _visible(r.get(c, "")) for c in cols} for r in rows] # one line per row: a newline would forge one width = {c: max(len(label[c]), *(len(r[c]) for r in cells)) for c in cols} print(" ".join(label[c].ljust(width[c]) for c in cols)) print(" ".join("-" * width[c] for c in cols)) for r in cells: print(" ".join(r[c].ljust(width[c]) for c in cols)) def _of(current, limit, as_bytes=False): """'2 of 3', '2.2 kB of 5.0 GB', 'not measured yet of 5.0 GB'.""" fmt = fmt_bytes if as_bytes else (lambda n: "-" if n is None else str(n)) return "%s of %s" % (fmt(current) if current is not None else "not measured yet", fmt(limit)) def emit_usage_human(args, out, extra_tables=()): """GET /v1/usage for a person (review 2026-09-20 night, item 8: the dict/list values used to print as JSON blobs): the scalars, then one table per section -- limits, projects, organizations, the per-catalog footprint -- the way the per-catalog view prints. `extra_tables` are (title, rows, columns, headers) appended by the caller (whoami adds what the caller holds on each catalog).""" for k, v in out.items(): if not isinstance(v, (dict, list)): print("%-26s %s" % (k, v)) limits = out.get("limits") or {} if limits: print("\nlimits") detail = out.get("limits_detail") or {} enforced = lambda k: {True: "yes", False: "no (guideline)"}.get((detail.get(k) or {}).get("enforced"), "-") # noqa: E731 _table([{"limit": k, "value": fmt_bytes(v) if k.endswith("_bytes") else v, "enforced": enforced(k)} for k, v in limits.items()]) projects = out.get("projects") or [] if projects: print("\nprojects") _table([{"project": p.get("name"), "project_id": p.get("project_id"), "org_id": p.get("org_id") or "-", "catalogs": _of((p.get("warehouses") or {}).get("current"), (p.get("warehouses") or {}).get("limit")), "stored": _of((p.get("storage_bytes") or {}).get("current"), (p.get("storage_bytes") or {}).get("limit"), True), "public stored": _of((p.get("public_storage_bytes") or {}).get("current"), (p.get("public_storage_bytes") or {}).get("limit"), True)} for p in projects]) orgs = out.get("organizations") or [] if orgs: print("\norganizations") _table([{"org_id": o.get("org_id"), "your role": o.get("role") or "-", "stored": _of((o.get("storage_bytes") or {}).get("current"), (o.get("storage_bytes") or {}).get("limit"), True), "public stored": _of((o.get("public_storage_bytes") or {}).get("current"), (o.get("public_storage_bytes") or {}).get("limit"), True)} for o in orgs]) cats = [{"catalog": w.get("name"), "catalog id": _cid(w), "project": p.get("name"), "tier": w.get("tier"), "stored": "not measured yet" if w.get("unmetered") else fmt_bytes(w.get("bytes")), "objects": "-" if w.get("objects") is None else _all_objects(w), "measured": w.get("measured_at") or "-"} for p in projects for w in p.get("warehouse_storage") or []] if cats: print("\ncatalogs") _table(cats) for title, rows, columns, headers in extra_tables: print("\n" + title) _table(rows, columns, headers) # ---------------------------------------------------------------- schema shorthand ICEBERG_TYPES = { "boolean", "int", "long", "float", "double", "date", "time", "timestamp", "timestamptz", "timestamp_ns", "timestamptz_ns", "string", "uuid", "binary", "variant", # format-version 3 only; the API answers 400 with the remedy when the table is v2 "geometry", "geography", } def parse_columns(specs): """`--column event_time:timestamptz:required` -> an Iceberg struct schema with field ids. Hand-assigning field-ids is exactly the kind of detail an agent gets wrong, so it is done here. """ fields, identifiers = [], [] for i, spec in enumerate(specs, start=1): # the type's parameters may hold colons (geometry(EPSG:28992), geography(OGC:CRS84, spherical)), # so the spec is not simply split on ":" m = re.match(r"^([^:]+):([A-Za-z_]+(?:\([^)]*\)|\[[^\]]*\])?)(?::(.*))?$", spec) if not m: die("--column wants name:type[:required][:identifier], got %r" % spec) name, typ = m.group(1), m.group(2) flags = set(p.lower() for p in (m.group(3) or "").split(":") if p) if typ.startswith(("decimal(", "fixed[", "geometry(", "geography(")): pass # parameterised types pass through untouched (geometry(EPSG:28992), geography(OGC:CRS84, spherical)) elif typ not in ICEBERG_TYPES: die("Unknown Iceberg type %r in %r.\nKnown: %s" % (typ, spec, ", ".join(sorted(ICEBERG_TYPES)))) unknown = sorted(flags - {"required", "identifier"}) if unknown: # a misspelt flag used to be dropped: the column came out nullable, not an identifier, or in the default CRS (#2988) hint = ("\nA CRS goes inside the type: %s(%s)." % (typ, ":".join((m.group(3) or "").split(":")[:2])) if typ in ("geometry", "geography") and (m.group(3) or "").upper().startswith(("EPSG", "OGC")) else "") die("Unknown column flag %s in %r: the flags are required and identifier " "(name:type[:required][:identifier]).%s" % (", ".join(map(repr, unknown)), spec, hint)) required = "required" in flags fields.append({"id": i, "name": name, "required": required, "type": typ}) if "identifier" in flags: if not required: die("An identifier column must also be required: %r" % spec) identifiers.append(i) return {"type": "struct", "schema-id": 0, "identifier-field-ids": identifiers, "fields": fields} # ---------------------------------------------------------------- commands def cmd_agent_renamed(args): """`lhbox agent revoke` was the tokens' verb until 0.4.0: say where it went; nothing is sent.""" die_json("renamed", "`lhbox agent revoke` revoked tokens until CLI 0.4.0; tokens are `lhbox token revoke %s` now. " "`lhbox agent` manages hosted agents: `lhbox agent delete` removes one." % (getattr(args, "ref", "") or ""), EXIT_USAGE, remedy="lhbox token revoke " + (getattr(args, "ref", "") or "")) def _saved_connection(args): """The credentials entry for this API, or None. An entry written before the rename of 2026-09-29 (CLI 0.3.x) says agent_id / kind agent: it is read with the new names, so `lhbox --json login` answers connection.token_id on a machine that connected before the upgrade too (high review of #752).""" entry = saved_credentials().get(args.url.rstrip("/")) or None return _renamed_entry(entry) if entry else None def _renamed_entry(entry): entry = dict(entry) if entry.get("kind") == "agent": entry["kind"] = "token" if "agent_id" in entry and "token_id" not in entry: entry["token_id"] = entry.pop("agent_id") conn = entry.get("connection") if isinstance(conn, dict) and "agent_id" in conn and "token_id" not in conn: conn = dict(conn) conn["token_id"] = conn.pop("agent_id") entry["connection"] = conn return entry def _key_status(args, key): """Does a saved key still work? GET /v1/usage with it -> (status, body); 0 when the API is unreachable.""" # days=1: no caller of this check reads the per-catalog history, and the default 7 days reads 7x the samples (#3517) url = args.url.rstrip("/") + "/v1/usage?days=1" req = urllib.request.Request(url, method="GET") req.add_unredirected_header("Authorization", "Bearer " + key) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): _die_timeout("GET", "/v1/usage", 30) # the saved-key check is a read (#2507) except urllib.error.HTTPError as e: try: return e.code, json.loads(e.read().decode() or "{}") except ValueError: return e.code, {} except urllib.error.URLError as e: _die_unreachable("GET", url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url("GET", "/v1/usage", e) def _level_words(level): return "read and write" if level == "write" else "read only" def _key_id_of(key): """al_live__ -> the key id (what `lhbox api-key revoke` takes), else None.""" parts = (key or "").split("_") return parts[2] if len(parts) >= 4 and parts[:2] == ["al", "live"] and parts[2] else None def _report_signed_in(args, entry, saved_to, key, me, reused): """A saved key that is the person's own (the browser or code login since 2026-11-02): who it signs in as and the person's revoke path, never a connection's (feedback 2026-11-02: it printed connection null, key_id null and pointed at Connections and `lhbox token revoke`).""" key_id = entry.get("key_id") or _key_id_of(key) revoke = "the account page, Settings > Access keys" + ("; or `lhbox api-key revoke --key-id %s`" % key_id if key_id else "") who = me.get("display_name") or me.get("email") if _want_json(args): out = {"connected": True, "reused": reused, "kind": "human", "signed_in_as": who, "connection": None, "warehouse_id": entry.get("warehouse_id"), "saved_to": saved_to, "profile": active_profile(False), "key_id": key_id, "api_key_masked": mask_key(key) if key else None, "revoke": revoke} if getattr(args, "show_key", False) and key: out["api_key"] = key print_json(out) return print("%s as %s (your own key: everything you can do on the website)." % ("Still signed in" if reused else "Signed in", who or "you")) print("Saved to %s, profile %s. Revoke: %s." % (saved_to, active_profile(False), revoke)) if getattr(args, "show_key", False) and key: print("api_key: %s" % key) def _report_connection(args, entry, saved_to, reused=False, key=None, downgraded=None, me=None): """`lhbox login`'s answer: what is connected, where the key went, how to revoke. The key itself is printed only with --show-key (docs/agent-setup.md: credentials stay out of the conversation). `downgraded`: the catalogs approved below what was asked -- a warning on stderr with the remedy, and `downgraded: true` in JSON. The person's own key (`me` from GET /v1/usage says kind human) is reported by _report_signed_in.""" if (me or {}).get("kind") == "human" or (entry.get("kind") == "human" and not entry.get("connection")): return _report_signed_in(args, entry, saved_to, key, me or {}, reused) conn = entry.get("connection") or {} if downgraded: print("warning: approved with less than this login asked for: %s. Writes there will be refused. Ask the person " "to raise it on the account page (Connections), or run `lhbox login --new` and have them tick write." % ", ".join("%s got %s, asked %s" % (d["name"], d["got"] or "nothing (left out)", d["asked"]) for d in downgraded), file=sys.stderr) whs = conn.get("warehouses") or ([{"warehouse_id": entry.get("warehouse_id"), "name": entry.get("warehouse_id"), "level": "write"}] if entry.get("warehouse_id") else []) if _want_json(args): out = {"connected": True, "reused": reused, "connection": conn or None, "warehouse_id": _cid(whs[0]) if whs else None, "saved_to": saved_to, "profile": active_profile(False), "key_id": entry.get("key_id"), "api_key_masked": mask_key(key) if key else None, "revoke": "your account page, Connections; or `lhbox token revoke`"} if downgraded: out["downgraded"] = True out["downgraded_catalogs"] = downgraded if getattr(args, "show_key", False) and key: out["api_key"] = key print_json(out) return names = ", ".join("%s (%s)" % (w.get("name") or _cid(w), _level_words(w.get("level"))) for w in whs) or "your catalog" print("%s %s as %s." % ("Still connected to" if reused else "Connected to", names, conn.get("name") or "this machine")) print("Saved to %s, profile %s. Revoke from your account page (Connections)." % (saved_to, active_profile(False))) if getattr(args, "show_key", False) and key: print("api_key: %s" % key) CAMPAIGN_PART = re.compile(r"^[A-Za-z0-9._-]{1,64}$") def parse_login_campaign(value): """--campaign SOURCE[/MEDIUM[/CAMPAIGN[/CONTENT]]] -> the API's `campaign` object, or None. The tags of the link that brought the person to the site (web/nav.js writes them into the login command it shows); an empty part is skipped. Malformed: a usage error before any request (operations/04-chatgpt-ads.md).""" if value is None: return None parts = value.split("/") out = {k: v for k, v in zip(("source", "medium", "campaign", "content"), parts) if v} if len(parts) > 4 or not out or not all(CAMPAIGN_PART.match(v) for v in out.values()): die("--campaign takes SOURCE[/MEDIUM[/CAMPAIGN[/CONTENT]]], each 1 to 64 letters, digits, '.', '_' or '-' " "(got %r)." % value[:80], EXIT_USAGE) return out def cmd_login(args): """Connect this machine to your catalog (docs/login.md, docs/agent-setup.md). Default: the device flow against this API -- a URL and a code are printed (and the browser opened when there is one), the human sees a consent screen on the account page (this machine's name, the catalog, the level, which they may lower) and approves; the CLI polls and receives the key of a NEW AGENT named after this machine, holding exactly the approved grants -- never the person's own key. The key is saved to the credentials file and not printed (--show-key prints it). A saved key that still works is reused (--new forces a fresh authorisation). `--issuer` keeps the OpenID Connect device flow of an external issuer (self-hosted deployments with their own IdP). Waiting (the third simulated user, STATE.md 2026-09-21: `login` blocked up to 15 minutes with no way out): the default waits until the code expires (the API's expires_in, 15 minutes) and prints one line every 60 s ("still waiting for approval at , min left"); `--no-wait` prints the page and the code, keeps the device code in the credentials file under `pending_device` (the resume token; never printed) and exits 0; `--resume` polls that pending login ONCE and completes it, or says it is still pending (exit 3, the credential is still missing); `--resume --wait` polls until it is decided.""" _before_minting(args) # before anything is minted: a refused save would only come after (#2573, #2640) if getattr(args, "client_credentials", False): return _login_client_credentials(args) if args.issuer is not None or getattr(args, "sso", None): return _login_oidc(args) if getattr(args, "resume", False): return _login_resume(args) saved = _saved_connection(args) if saved and saved.get("api_key") and not getattr(args, "new", False): status, me = _key_status(args, saved["api_key"]) if status == 200: me = me if isinstance(me, dict) else {} _report_connection(args, saved, CRED_FILE, reused=True, key=saved["api_key"], me=me) asked_more = bool(getattr(args, "level", None) or getattr(args, "manage_agents", False)) if me.get("kind") == "token": # a key from the code login before 2026-11-02 acts with its own grants; a login now is the person print("This saved key is a token limited to what was approved for it%s. To sign in as yourself instead " "(everything you can do on the website, agents included): lhbox login --new" % ("; --level/--manage-agents did not change it" if asked_more else ""), file=sys.stderr) elif asked_more: print("note: --level and --manage-agents are no longer used: this saved key is already yours.", file=sys.stderr) return if status == 429 or status >= 500: # busy or failing says nothing about the key (#2087): a new authorisation here replaced a working key and # left its connection live with nobody holding it. Exit 5 (retry), the saved login untouched. _fail("GET", "/v1/usage", status, me if isinstance(me, dict) else {}) print("The saved key for %s no longer works (HTTP %d); starting a new authorisation." % (args.url.rstrip("/"), status), file=sys.stderr) elif saved and saved.get("api_key"): # --new over a working key replaces it in this profile (lakehousebox#17: a second account overwrote the first); # said before the approval, so there is still time to stop and keep both print("This login replaces the key saved for %s in profile %s. To keep both accounts, stop here and run " "`lhbox --profile login` instead." % (args.url.rstrip("/"), active_profile(False)), file=sys.stderr) old = saved.get("token_id") or (saved.get("connection") or {}).get("token_id") if old: # a login makes no connection since 2026-11-02, so --new never adds "mac-garden 2"; the token it replaces # stays live until revoked (it may be in use elsewhere: never revoked by this command) print("The token connection it replaces (%s) keeps working until you revoke it: `lhbox token revoke %s`, or " "the account page (Connections)." % ((saved.get("connection") or {}).get("name") or old, old), file=sys.stderr) cfg = unauth_request(args, "GET", "/v1/auth/config", None) if not cfg.get("password_login"): issuers = [i for i in cfg.get("external_issuers", []) if i.get("device_authorization_endpoint")] if issuers: die("Password login is off on this deployment; log in through its identity provider: " "lhbox login --issuer %s" % issuers[0]["issuer"], EXIT_USAGE) die("This deployment has neither password login nor an identity provider with device login configured. " "Use `lhbox signup --email ...` instead.", EXIT_ERROR) # a login is yes or no since 2026-11-02 (the founder): it acts as the person. A call that asked for LESS (a catalog, # read only) is refused, never widened to the person's whole key (high review of #2476); one that asked for write # or agents gets that and more, and is told why the flag does nothing if getattr(args, "warehouse", None) or getattr(args, "level", None) == "read": die("`lhbox login` signs this computer in as you: it makes no key limited to some catalogs or to read. Make one " "on the website (Settings > Access keys) or with `lhbox token create --name --grant :read`, " "and use it as LHBOX_API_KEY. To sign in as yourself, run `lhbox login` without --catalog/--level.", EXIT_USAGE) if getattr(args, "level", None) or getattr(args, "manage_agents", False): print("note: --level and --manage-agents are no longer used: `lhbox login` signs this computer in as you.", file=sys.stderr) browser_why = _browser_login_blocker(args, cfg) if browser_why is None: return _login_browser(args, cfg) if browser_why: print("Using the code login (%s)." % browser_why, file=sys.stderr) hostname = socket.gethostname() body = {"client": "cli", "hostname": hostname, "client_name": getattr(args, "name", None) or hostname} campaign = parse_login_campaign(getattr(args, "campaign", None)) if campaign: body["campaign"] = campaign if getattr(args, "no_wait", False): body["relayed"] = True # the person approves when the relayed message reaches them: the code lives an hour dev = unauth_request(args, "POST", "/v1/auth/device", body) url = dev.get("verification_uri_complete") or dev.get("verification_uri") interval = int(dev.get("interval", 5)) expires_in = int(dev.get("expires_in", 900)) deadline = time.time() + expires_in no_wait = getattr(args, "no_wait", False) # the prompt goes to stderr: stdout stays JSON for a consumer that pipes this command # the link carries the code: the person checks it matches and approves with one click (the founder, 2026-11-15, #2462) print("To sign this computer in as you, open this page, check it shows the code %s, and allow it:\n %s\n%s" % (dev.get("user_code"), url, "(the code is valid for %d minutes)" % (expires_in // 60) if no_wait else "(waiting up to %d minutes; a line every 60 s says how long is left)" % (expires_in // 60)), file=sys.stderr, flush=True) _open_browser(url) if no_wait: # the resume token is the device code, kept in the credentials file and never printed: whoever holds it # receives the token's key once the person approves. The saved key (if any) stays in the entry. entry = dict(saved or {}) entry["pending_device"] = {"device_code": dev["device_code"], "user_code": dev.get("user_code"), "verification_uri": url, "expires_at": deadline, "interval": interval, "url": args.url.rstrip("/")} saved_to = save_credentials(args, entry) out = {"connected": False, "pending": True, "user_code": dev.get("user_code"), "verification_uri": url, "expires_in": expires_in, "expires_at": _iso_utc(deadline), "resume": "lhbox login --resume", "resume_wait": "lhbox login --resume --wait", "pending_device_saved_to": saved_to, "client_name": body["client_name"]} if _want_json(args): print_json(out) else: print("Approval pending: the person opens %s, checks the code %s and approves (valid %d minutes)." % (url, dev.get("user_code"), expires_in // 60)) print("Resume token saved to %s (pending_device; not shown). Then run: lhbox login --resume (polls once; --resume --wait waits)" % saved_to) return key = _device_poll(args, dev["device_code"], url, deadline, interval, wait=True) _finish_device_key(args, key) def _browser_login_blocker(args, cfg): """None when `lhbox login` should sign in through the browser (#2467: the person allows it, the key is theirs); else why not, as a phrase ("" when nothing needs saying): a scoped key was asked for (--catalog, --level, --manage-agents), --no-browser or --no-wait, a server without it, or no browser beside this CLI (an SSH session, a Linux box without a display), where the device flow's code is the way.""" if not cfg.get("cli_browser_login") or not cfg.get("web_base"): return "" if getattr(args, "no_browser", False): return "" if getattr(args, "no_wait", False) or getattr(args, "campaign", None): return "" if _env("NO_BROWSER"): return "" if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"): return "an SSH session: the browser is on another computer" if sys.platform.startswith("linux") and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) \ and "microsoft" not in pyplatform.release().lower(): return "no browser on this computer" return None CLI_LOGIN_WAIT = 600 def _login_browser(args, cfg): """`lhbox login` in the browser (#2467, RFC 8252): listen on 127.0.0.1, open the account page, the person allows it there, the browser comes back here with a one-time code, traded with the PKCE verifier only this process holds for THE PERSON'S OWN KEY (acts as them, ends after 30 days). The link is printed too: an agent on this computer can hand it to the person, the redirect still lands here.""" import http.server import secrets as _secrets verifier = _secrets.token_urlsafe(48) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() state = _secrets.token_urlsafe(16) got = {} done = threading.Event() ended = threading.Event() # the code traded (or not): only then does the browser hear how it ended outcome = {} class Handler(http.server.BaseHTTPRequestHandler): timeout = 10 # a connection that sends nothing is dropped, never held def log_message(self, *a): pass def do_GET(self): # noqa: N802 - the stdlib's name q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) ok = (q.get("state") or [""])[0] == state and urllib.parse.urlsplit(self.path).path == "/callback" if ok and not done.is_set(): got.update({k: v[0] for k, v in q.items()}) done.set() if ok: # back to the account page, which says how it ended in the site's own design (gcloud does the same), # once the code is traded and the key saved (high review of #2474); nothing of the code or state goes ended.wait(90) end = outcome.get("end") or "failed=1" self.send_response(302) self.send_header("Location", cfg["web_base"].rstrip("/") + "/app/cli-login?" + end) self.send_header("Content-Length", "0") self.end_headers() return body = b"Not a LakehouseBox login. You can close this tab." self.send_response(400) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) # one thread per connection: a browser opens speculative connections to the address it will visit and sends # nothing on them; a one-at-a-time server read the first forever and never reached the /callback behind it # (lhbox login hung until it timed out, on Chrome, intermittently) server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) server.daemon_threads = True threading.Thread(target=server.serve_forever, name="lhbox-login", daemon=True).start() redirect = "http://127.0.0.1:%d/callback" % server.server_address[1] hostname = socket.gethostname() q = urllib.parse.urlencode({"redirect_uri": redirect, "state": state, "code_challenge": challenge, "client_name": getattr(args, "name", None) or hostname, "hostname": hostname}) url = cfg["web_base"].rstrip("/") + "/app/cli-login?" + q print("Opening your browser to sign in. If it does not open, open this link on THIS computer:\n %s\n" "(waiting up to %d minutes; `lhbox login --no-browser` signs in with a code instead)" % (url, CLI_LOGIN_WAIT // 60), file=sys.stderr, flush=True) try: webbrowser.open(url, new=2) except Exception: # noqa: BLE001 - the link was printed pass def close(end): outcome["end"] = end ended.set() time.sleep(0.5) # the redirect leaves before the listener stops server.shutdown() server.server_close() if not done.wait(CLI_LOGIN_WAIT): close("failed=1") die("login timed out: nobody allowed it in the browser within %d minutes. Run `lhbox login` again " "(or `lhbox login --no-browser` when the browser is on another computer)." % (CLI_LOGIN_WAIT // 60), EXIT_AUTH) if got.get("error"): close("denied=1" if got["error"] == "access_denied" else "failed=1") die("login refused in the browser (%s)." % got["error"], EXIT_AUTH) status, out = _raw_post(args, "/v1/auth/cli/token", {"code": got.get("code"), "code_verifier": verifier, "redirect_uri": redirect}) if status != 200: close("failed=1") _fail("POST", "/v1/auth/cli/token", status, out) # saved FIRST: the key is live and the person was mailed about it; an onboarding that fails next (Terms, a 5xx) # must not leave it held by nobody (high review of #2472) _save_minted(args, {"api_key": out["api_key"], "key_id": _key_id_of(out["api_key"]), "kind": "human"}, drop_pending=True) close("done=1" + ("&until=" + urllib.parse.quote(str(out["expires_at"])[:10]) if out.get("expires_at") else "")) _finish_login(args, out["api_key"], out.get("label"), saved=True) def parse_login_catalogs(specs, default_level): """`--catalog NAME[:LEVEL]` (repeatable; a name or a warehouse_id) -> [{name, level}]; LEVEL read|write, the command's --level when absent. A catalog name holds no colon, so the last one separates the level.""" out = [] for spec in specs or []: name, sep, level = spec.rpartition(":") if not sep: name, level = spec, default_level if not name or level not in ("read", "write"): die("--catalog wants NAME[:read|write], got %r" % spec, EXIT_USAGE) out.append({"name": name, "level": level}) return out def _iso_utc(epoch): return datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def _minutes_left(deadline): return max(0, int((deadline - time.time() + 59) // 60)) def _device_poll(args, device_code, url, deadline, interval, wait, what="login"): """Poll POST /v1/auth/device/token. wait=True: until the human decides or the code expires (the deadline is the code's expiry, never longer), a stderr line every 60 s with the minutes left; the answer, or die. wait=False: one poll; the answer, or None while the approval is pending (slow_down counts as pending).""" next_note = time.time() + 60 while True: if wait: time.sleep(interval) # while waiting, a lost network (a DNS blip, a laptop waking) or a busy server is not the end: polled again # until the code's own expiry (feedback 2026-11-02: one DNS error ended a --resume --wait at once) _SILENT.on = True try: status, body = _raw_post(args, "/v1/auth/device/token", {"device_code": device_code}) except SystemExit as e: if e.code != EXIT_SERVER or time.time() >= deadline: _SILENT.on = False status, body = _raw_post(args, "/v1/auth/device/token", {"device_code": device_code}) else: status, body = 0, {} finally: _SILENT.on = False if (status == 0 or status == 429 or status >= 500) and time.time() < deadline: if time.time() >= next_note: print("cannot reach %s right now; still polling, %d min left" % (args.url.rstrip("/"), _minutes_left(deadline)), file=sys.stderr, flush=True) next_note = time.time() + 60 continue else: status, body = _raw_post(args, "/v1/auth/device/token", {"device_code": device_code}) if status == 200: return body err = (body.get("error") or {}) if isinstance(body, dict) else {} code = err.get("code", "") if code in ("authorization_pending", "slow_down"): if code == "slow_down": interval = max(interval + 5, int(err.get("interval") or 0)) if not wait: return None if time.time() >= deadline: die("%s timed out: the code expired before it was approved. Run `lhbox %s` again." % (what, what), EXIT_AUTH) if time.time() >= next_note: print("still waiting for approval at %s, %d min left" % (url, _minutes_left(deadline)), file=sys.stderr, flush=True) next_note = time.time() + 60 continue if code == "expired_token": if time.time() < deadline - 30: # the deadline is the server's expires_in from the start: a margin for latency # the API says expired_token for a code already used too: its key went to another poll (a second lhbox # on the same pending login, or an answer lost on the way), never "not confirmed in time" die("%s ended: the code was already used, before its expiry. If no other lhbox picked up its key, run " "`lhbox %s` again." % (what, what), EXIT_AUTH) die("%s timed out: the code was not confirmed in time. Run `lhbox %s` again." % (what, what), EXIT_AUTH) if code == "access_denied": die("%s refused on the device page." % what, EXIT_AUTH) _fail("POST", "/v1/auth/device/token", status, body) def _finish_device_key(args, key): if key.get("connection"): _finish_connection(args, key) # a control plane from before 2026-11-02, or a claim else: # the person's key (the code login acts as them since 2026-11-02): _finish_login saves it before onboarding _finish_login(args, key["api_key"], key.get("label")) def _login_resume(args): """`lhbox login --resume`: the login `--no-wait` left pending, polled once (or until decided with --wait). Completing it saves the token's key and drops pending_device; an expired code is dropped with the remedy.""" entry = _saved_connection(args) or {} pend = entry.get("pending_device") # a claim (lhbox claim) is kept in the same place; its messages name the claim (high review of #1238) what = "claim" if (pend or {}).get("flow") == "claim" or getattr(args, "fn", None) is cmd_claim else "login" start = "lhbox claim" if what == "claim" else "lhbox login --no-wait" if not pend or not pend.get("device_code"): die("No %s is pending for %s. Start one with: %s" % (what, args.url.rstrip("/"), start), EXIT_USAGE) deadline = float(pend.get("expires_at") or 0) url = pend.get("verification_uri") or "" if time.time() >= deadline: entry.pop("pending_device", None) save_credentials(args, entry, drop_pending=True) die("The pending %s's code %s expired before it was approved. Run `%s` again and send the new link." % (what, pend.get("user_code"), start), EXIT_AUTH) key = _device_poll(args, pend["device_code"], url, deadline, int(pend.get("interval") or 5), wait=bool(getattr(args, "wait", False)), what=what) args._asked_level, args._asked_catalogs = pend.get("requested_level") or "write", pend.get("catalogs") or [] if key is None: mins = _minutes_left(deadline) if _want_json(args): print_json({"connected": False, "pending": True, "user_code": pend.get("user_code"), "verification_uri": url, "minutes_left": mins, "resume": "lhbox login --resume", "resume_wait": "lhbox login --resume --wait"}) print("still waiting for approval at %s, %d min left (lhbox %s --resume polls again; --resume --wait waits)" % (url, mins, what), file=sys.stderr) sys.exit(EXIT_AUTH) _finish_device_key(args, key) def _finish_connection(args, key): """The device flow answered with a token's key and its connection: save both (always -- the whole point is that the key never travels through the terminal), then report without the key.""" conn = key.get("connection") or {} whs = conn.get("warehouses") or [] entry = {"api_key": key["api_key"], "key_id": key.get("key_id"), "kind": "token", "token_id": conn.get("token_id"), "connection": {"token_id": conn.get("token_id"), "name": conn.get("name"), "org_id": conn.get("org_id"), "warehouses": [{"warehouse_id": _cid(w), "name": w.get("name"), "level": w.get("level")} for w in whs]}, "warehouse_id": _cid(whs[0]) if whs else None} _note_other_org(args, conn.get("org_id")) saved_to = _save_minted(args, entry, drop_pending=True) # this IS the pending login's completion _report_connection(args, entry, saved_to, key=key["api_key"], downgraded=_downgraded(args, whs)) def _note_other_org(args, org_id): """Say so on stderr when the key about to be saved belongs to another organisation than the saved one it replaces (lakehousebox#17): the earlier key is gone from this profile, and --profile is how two accounts live side by side.""" prev = saved_credentials().get(args.url.rstrip("/")) or {} prev_org = (prev.get("connection") or {}).get("org_id") if prev.get("api_key") and prev_org and org_id and prev_org != org_id: print("Note: the key saved for %s in profile %s belonged to another organisation; it was replaced. To use both, " "keep each in its own profile: `lhbox --profile login`." % (args.url.rstrip("/"), active_profile(False)), file=sys.stderr) def _expires_in(iso): """Seconds until an ISO-8601 UTC time (2026-10-15T09:00:00.000Z), or None when it does not parse.""" try: t = datetime.datetime.strptime(iso, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=datetime.timezone.utc) except (TypeError, ValueError): return None return int((t - datetime.datetime.now(datetime.timezone.utc)).total_seconds()) def _hours_words(seconds): if seconds is None: return "an unknown time" if seconds <= 0: return "no time" h = seconds // 3600 return ("%d h %02d min" % (h, (seconds % 3600) // 60)) if h else "%d min" % max(1, seconds // 60) def cmd_new(args): """An agent with no account and no person (research/70): an unclaimed organisation, its catalog and a write key, saved like `lhbox login` saves one and never printed. Nobody owns it until a person claims it; it is deleted with its data when its time runs out (72 h).""" _before_minting(args) # before the organisation and its key are made (#2573, #2640) # malformed tags are a usage error before anything else, never steered towards --force (high review of #1250) campaign = parse_login_campaign(getattr(args, "campaign", None)) if getattr(args, "api_key", None) or _env("API_KEY"): # the new key would be saved, and the one given here would still be the one every command uses (high review of #1231) die_json("key_in_use", "A key is given with --api-key or LHBOX_API_KEY; `lhbox new` saves its key to the credentials " "file, and the given key would still win.", EXIT_USAGE, remedy="Unset LHBOX_API_KEY (and drop --api-key), then run `lhbox new` again.") if (saved_credentials().get(args.url.rstrip("/")) or {}).get("api_key") and not args.force: die_json("already_connected", "This machine already holds a key for %s; `lhbox new` would replace it." % args.url.rstrip("/"), EXIT_USAGE, remedy="Use the catalog you have (`lhbox whoami`), or keep both: `lhbox --profile scratch new` " "(or --force to replace the saved key).") hostname = socket.gethostname() body = {"type": "anonymous", "client": "cli", "hostname": hostname, "client_name": hostname} if campaign: body["campaign"] = campaign out = unauth_request(args, "POST", "/v1/agent/identity", body, timeout=300) conn = out.get("connection") or {} whs = conn.get("warehouses") or [] org = out.get("organization") or {} entry = {"api_key": out["api_key"], "key_id": out.get("key_id"), "kind": "token", "token_id": conn.get("token_id"), "connection": {"token_id": conn.get("token_id"), "name": conn.get("name"), "org_id": conn.get("org_id"), "warehouses": [{"warehouse_id": _cid(w), "name": w.get("name"), "level": w.get("level")} for w in whs]}, "warehouse_id": _cid(whs[0]) if whs else None, "unclaimed": {"org_id": org.get("org_id"), "expires_at": out.get("expires_at")}} saved_to = _save_minted(args, entry, drop_pending=True) name = (out.get("catalog") or {}).get("name") or (whs[0].get("name") if whs else "lakehouse") terms = out.get("terms") or {} if _want_json(args): print_json({"created": True, "unclaimed": True, "organization": org, "catalog": out.get("catalog"), "expires_at": out.get("expires_at"), "limits": out.get("limits"), "saved_to": saved_to, "key_id": out.get("key_id"), "api_key_masked": mask_key(out["api_key"]), "terms": terms, "how_to_use": out.get("how_to_use"), "next": out.get("next")}) return print("Created catalog %s for this agent, with no account. Write access; the key is saved to %s." % (name, saved_to)) print("Nobody owns it yet: it is deleted with its data in %s (%s) unless a person claims it." % (_hours_words(_expires_in(out.get("expires_at"))), out.get("expires_at"))) print("Until then: at most 1 GB, nothing public, data only (no new keys, sharing or sinks).") print("Next: lhbox duckdb --catalog %s · when a person is there to keep it: lhbox claim" % name) if terms.get("url"): print("Creating it accepted the Terms of Service (%s) and the Acceptable Use Policy." % terms["url"]) def cmd_claim(args): """A person keeps the catalog `lhbox new` made (research/70): a link and a code for them; they sign up or log in, type the code and choose where the catalog goes. The pending claim is saved like `login --no-wait` saves a login (pending_device); `--wait` waits for the decision, `--resume` collects it later. The answer is this machine's NEW key, saved in place: the current one stops working at the claim.""" _before_minting(args) # before the claim starts (#2573, #2640) if getattr(args, "api_key", None) or _env("API_KEY"): # the claim revokes the key in use and saves the new one to the credentials file; a key given here would still # win and be refused from then on (high review of #1238) die_json("key_in_use", "A key is given with --api-key or LHBOX_API_KEY; the claim saves the new key to the credentials " "file, and the given (revoked) key would still win.", EXIT_USAGE, remedy="Unset LHBOX_API_KEY (and drop --api-key), then run `lhbox claim` again.") if getattr(args, "resume", False): return _login_resume(args) entry = _saved_connection(args) or {} dev = request(args, "POST", "/v1/agent/identity/claim") url = dev.get("verification_uri_complete") or dev.get("verification_uri") interval, expires_in = int(dev.get("interval", 5)), int(dev.get("expires_in", 900)) deadline = time.time() + expires_in entry["pending_device"] = {"device_code": dev["device_code"], "user_code": dev.get("user_code"), "verification_uri": url, "expires_at": deadline, "interval": interval, "url": args.url.rstrip("/"), "requested_level": "write", "catalogs": [], "flow": "claim"} saved_to = save_credentials(args, entry) cats = ", ".join((dev.get("claim") or {}).get("catalogs") or []) or "the catalog" say = ("To keep %s, the person opens this page, signs up or logs in, checks the code %s, chooses where to keep it, and " "ticks write if this agent should keep writing:\n %s\n(the code is valid for %s)" % (cats, dev.get("user_code"), url, _hours_words(expires_in))) if getattr(args, "wait", False): print(say, file=sys.stderr, flush=True) _open_browser(url) key = _device_poll(args, dev["device_code"], url, deadline, interval, wait=True, what="claim") _finish_device_key(args, key) return if _want_json(args): print_json({"claimed": False, "pending": True, "user_code": dev.get("user_code"), "verification_uri": url, "expires_in": expires_in, "catalogs": (dev.get("claim") or {}).get("catalogs"), "resume": "lhbox claim --resume", "resume_wait": "lhbox claim --resume --wait", "pending_device_saved_to": saved_to}) return print(say) print("Then run: lhbox claim --resume --wait (saves this machine's new key; the current one stops at the claim)") def cmd_status(args): """Whether this machine's catalog is still unclaimed, and the time it has left.""" out = request(args, "GET", "/v1/agent/status") if _want_json(args): print_json(out) return if not out.get("unclaimed"): print("This key belongs to an account: nothing expires.") return print("Unclaimed: made by an agent without an account. Deleted with its data in %s (%s) unless a person claims it." % (_hours_words(out.get("seconds_left")), out.get("expires_at"))) def cmd_discard(args): """An unclaimed catalog (lhbox new) deleted now, with its data and every key, instead of at its expiry (#1765: logout, catalog delete and account delete are all claim_required there, so a leaked key lived 72 h). A purge: --yes, or a person at a terminal says y; without either it is refused, as a drop is, never run with a warning.""" st = request(args, "GET", "/v1/agent/status") if not st.get("unclaimed"): die_json("not_unclaimed", "This key belongs to an account a person owns: lhbox discard ends only a catalog `lhbox " "new` made that nobody has claimed.", EXIT_LIMIT, remedy="An admin deletes a catalog with `lhbox catalog delete`; `lhbox logout` revokes this machine's key.") oid = st["org_id"] what = "Discard organisation %s: its catalog and every table and file in it are deleted now, and this key stops working" % oid if not getattr(args, "yes", False): if sys.stdin.isatty() and sys.stdout.isatty() and not args.json: if _ask("%s? This cannot be undone. [y/N] " % what).strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was changed.", EXIT_USAGE) else: die("%s: pass --yes to confirm (no terminal to ask)." % what, EXIT_USAGE) used = api_key(args) out = request(args, "DELETE", "/v1/agent/identity", {"confirm": oid}) # the saved key is dead now: forget it, as logout does -- only when it is the key this discard used, never another # account's login saved for the same URL while LHBOX_API_KEY or --api-key named the unclaimed one (high review of #1772) url = args.url.rstrip("/") with _cred_lock(): raw = _read_file() # lenient: the delete is done; an unreadable file holds no `used`, so nothing is written profiles = _profiles_of(raw) saved = profiles.get(active_profile(), {}) if (saved.get(url) or {}).get("api_key") == used: saved.pop(url) _write_file(_raw_of(profiles, raw.get("active"))) out["removed_from"] = CRED_FILE_SHOWN emit(args, out) UNCLAIMED_NOTICE_SECONDS = 24 * 3600 # commands kept out of `lhbox --help` and the CLI reference until the service offers them (research/70: AL_AGENT_SIGNUP) UNLISTED_COMMANDS: tuple = () def _unclaimed_in_use(args): """The saved `unclaimed` record (lhbox new: org_id, expires_at) when the key this command uses is that saved key, else None. Read from the credentials file, no request: the claim replaces the entry and drops the record, and a key given with --api-key or LHBOX_API_KEY is not judged by it (the server answers for that one, #1763).""" try: entry = saved_credentials().get(args.url.rstrip("/")) or {} rec = entry.get("unclaimed") if not rec or not entry.get("api_key") or _api_key_or_none(args) != entry["api_key"]: return None left = _expires_in(rec.get("expires_at")) return None if left is not None and left <= 0 else rec # expired: the server's own answer says so except Exception: # noqa: BLE001 -- a hint never fails a command return None def unclaimed_notice(args): """After any command, on stderr: the time left once under a day, when the saved key belongs to an unclaimed organisation (lhbox new). Read from the credentials file: no request.""" if getattr(args, "fn", None) in (cmd_new, cmd_status, cmd_claim): return try: left = _expires_in(((saved_credentials().get(args.url.rstrip("/")) or {}).get("unclaimed") or {}).get("expires_at")) except Exception: # noqa: BLE001 -- a notice never fails a command return if left is not None and left < UNCLAIMED_NOTICE_SECONDS: print("note: this catalog has no owner and is deleted with its data in %s unless a person claims it." % _hours_words(left), file=sys.stderr) def _downgraded(args, granted): """The catalogs that got LESS than this login asked for (the approval page preselects read; write is the person's explicit choice since security audit M7): [{name, asked, got}]. What was asked comes from this run's flags, or from the pending login --no-wait saved (a --resume has none of them).""" asked_level = getattr(args, "_asked_level", None) or getattr(args, "level", None) or "write" asked = {w["name"]: w["level"] for w in (getattr(args, "_asked_catalogs", None) or parse_login_catalogs(getattr(args, "warehouse", None), asked_level))} rank = {"none": 0, "read": 1, "write": 2} out = [] for w in granted or []: want = asked.get(w.get("name")) or asked.get(_cid(w)) or asked_level if rank.get(w.get("level") or "none", 0) < rank.get(want, 0): out.append({"name": w.get("name") or _cid(w), "asked": want, "got": w.get("level")}) # a catalog this login named that the approval left out entirely (round 2 of the M7 review): got nothing have = {w.get("name") for w in granted or []} | {_cid(w) for w in granted or []} for name, want in asked.items(): if name not in have: out.append({"name": name, "asked": want, "got": None}) return out def _finish_login(args, api_key, label=None, base=None, saved=False): """The person's key (the browser, the code login, an identity provider): make sure a catalog exists, save the key (always), report without it unless --show-key. base: the entry to save (an identity provider's login records which one, so a re-run can reuse it); saved: the caller saved it already (the browser path, a reused key).""" args.api_key = api_key entry = dict(base or {}, api_key=api_key, key_id=_key_id_of(api_key), kind="human") # key_id: what logout revokes (#2492) saved_to = CRED_FILE if not saved: # saved FIRST, as the browser path does: an onboarding refused next (Terms, a 5xx, a timeout) must not leave the # key held by nobody (#2639); a re-run then reuses it (_login_oidc) instead of minting another saved_to = _save_minted(args, entry, drop_pending=True) ob = request(args, "POST", "/v1/onboard", {"engine": args.engine, "accept_terms": bool(args.accept_terms)}, timeout=300) # provisions a warehouse + two identities # a member who joined an organisation and was given no catalog yet (2026-11-12: a member reads no catalog until # given access) is logged in all the same: POST /v1/onboard answers no catalog (warehouse_id null, catalogs_held 0) # and a note saying what to do, which is passed on held = _cid(ob) if held: try: saved_to = save_credentials(args, dict(entry, warehouse_id=held), drop_pending=True) except OSError: pass # the key itself is saved already: only its catalog id is not, and it must never be revoked for that if _want_json(args): key_id = _key_id_of(api_key) out = {"connected": True, "kind": "human", "label": label, "warehouse_id": held, "created": ob["created"], "saved_to": saved_to, "key_id": key_id, "api_key_masked": mask_key(api_key), "revoke": "the account page, Settings > Access keys" + ("; or `lhbox api-key revoke --key-id %s`" % key_id if key_id else "")} if not held: out["catalogs_held"] = ob.get("catalogs_held", 0) if ob.get("note"): out["note"] = ob["note"] if getattr(args, "show_key", False): out["api_key"] = api_key print_json(out) return if held: print("Logged in. %s catalog %s (its warehouse_id). Key saved to %s (not shown; --show-key prints it)." % ("Created" if ob["created"] else "Found", held, saved_to)) else: print("Logged in. You hold no catalog yet. Key saved to %s (not shown; --show-key prints it)." % saved_to) print(ob.get("note") or "Create a catalog (lhbox catalog create ), or ask an admin of the organisation " "to give you one.") if getattr(args, "show_key", False): print("api_key: %s" % api_key) def _open_browser(url): """Open the device page when a human is plausibly at this terminal: stdin and stderr are terminals and LHBOX_NO_BROWSER is unset. Never fails the login: the URL was printed anyway.""" if _env("NO_BROWSER") or not (sys.stdin.isatty() and sys.stderr.isatty()): return try: webbrowser.open(url, new=2) except Exception: # noqa: BLE001 - best effort, by design pass def _raw_post(args, path, body): """One unauthenticated POST returning (status, parsed body) without exiting on an HTTP error: the device flow reads authorization_pending / slow_down out of 400 answers.""" url = args.url.rstrip("/") + path req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST") req.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): _die_timeout("POST", path, 30) except urllib.error.HTTPError as e: raw = e.read().decode() try: return e.code, json.loads(raw) except ValueError: return e.code, {"error": {"code": "http_%d" % e.code, "message": raw[:300]}} except urllib.error.URLError as e: if _is_timeout(e): _die_timeout("POST", path, 30, sent=False) _die_unreachable("POST", url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url("POST", path, e) def _login_oidc(args): """The external-issuer path: RFC 8628 against the identity provider named by GET /v1/auth/config, then its token is exchanged for an API key of ours. `--issuer` alone takes the first configured issuer. `--sso EMAIL` asks GET /v1/auth/realm which identity provider signs that address in (an organisation's own, research/74).""" if getattr(args, "sso", None): realm = unauth_request(args, "GET", "/v1/auth/realm?" + urllib.parse.urlencode({"email": args.sso}), None) if not realm.get("sso"): die("No organisation signs %s in with its own identity provider here. Use `lhbox login` instead." % args.sso, EXIT_NOTFOUND) if realm.get("provider") == "google": # a Google Workspace domain an organisation bound (research/82 §4): Google has no device flow for us, so the # person signs in on the account page, then `lhbox login` approves this device there app = site_url(args) + "/app/" msg = "This organisation signs in with Google: use Continue with Google at %s, then `lhbox login`." % app if _want_json(args): print_json({"sso": True, "provider": "google", "domain": realm.get("domain"), "url": app, "next": "lhbox login", "message": msg}) else: print(msg) return if not realm.get("device_authorization_endpoint"): die("The identity provider for %s could not be reached (%s); try again later." % (args.sso, realm.get("unavailable") or "no device endpoint"), EXIT_SERVER) iss = realm else: cfg = unauth_request(args, "GET", "/v1/auth/config", None) issuers = [i for i in cfg.get("external_issuers", []) if i.get("device_authorization_endpoint")] if not issuers: die("This deployment has no identity provider with device login configured. " "Use `lhbox login` (password login) or `lhbox signup --email ...` instead.", EXIT_ERROR) iss = issuers[0] if args.issuer: iss = next((i for i in issuers if i["issuer"] == args.issuer), None) or die("unknown issuer", EXIT_USAGE) saved = _saved_connection(args) or {} if saved.get("api_key"): status = 0 if not getattr(args, "new", False): status, _ = _key_status(args, saved["api_key"]) if status == 429 or status >= 500: _fail("GET", "/v1/usage", status, {}) # busy says nothing about the key (#2087): keep it, retry same = saved.get("issuer") == iss.get("issuer") and (not getattr(args, "sso", None) or saved.get("sso") == args.sso) if status == 200 and saved.get("kind") == "human" and same: # the person's own key, still working: a re-run (after `terms_required`, or a 5xx on onboarding) finishes with # it instead of minting another and leaving this one live with nobody holding it (#2639); --new mints anew print("Still signed in for %s (the saved key works); finishing with it. `lhbox login ... --new` signs in " "again." % args.url.rstrip("/"), file=sys.stderr) return _finish_login(args, saved["api_key"], args.label, base=saved, saved=True) if status in (0, 200): # a working key (--new, or a token) is replaced in this profile: said before the sign-in, as `login --new` does print("This login replaces the key saved for %s in profile %s, which keeps working until revoked (`lhbox " "logout` revokes it first). To keep both accounts, stop here and run `lhbox --profile login` " "instead." % (args.url.rstrip("/"), active_profile(False)), file=sys.stderr) # the key exchange below needs a RECENT sign-in at the provider (security review 2026-10-08): ask for one with # max_age=0 and prompt=login (OpenID Connect; Microsoft Entra ID documents only prompt=login; a provider may ignore # them in the device flow, or refuse them: then the request goes again without, and the exchange relies on the ID # token's auth_time or the operator's setting). The scope is the issuer's (GET /v1/auth/config): Entra needs its own # API scope, or it issues a Microsoft Graph token this deployment cannot verify (research/74) form = {"client_id": iss["client_id"], "scope": iss.get("scope") or "openid email profile"} try: dev = None # the fullest request first; a provider that refuses a parameter (400) is asked with less: prompt is not an RFC # 8628 device parameter, so max_age alone keeps the fresh sign-in for a provider that refuses only prompt for extra in ({"max_age": "0", "prompt": "login"}, {"max_age": "0"}, {}): try: dev = _idp_post(iss["device_authorization_endpoint"], dict(form, **extra)) break except urllib.error.HTTPError as e: if e.code != 400 or not extra: raise except urllib.error.HTTPError as e: die("identity provider refused the device login: HTTP %d %s" % (e.code, e.read().decode()[:300]), exit_code_for(e.code)) url = dev.get("verification_uri_complete") or dev.get("verification_uri") print("Open this in a browser and confirm the code %s:\n %s" % (dev.get("user_code"), url), file=sys.stderr, flush=True) _open_browser(url) interval = int(dev.get("interval", 5)); deadline = time.time() + int(dev.get("expires_in", 300)) token = None while time.time() < deadline: time.sleep(interval) try: token = _idp_post(iss["token_endpoint"], {"grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": dev["device_code"], "client_id": iss["client_id"]}, poll=True) break except (TimeoutError, socket.timeout): continue # one slow poll: the device code is still good until the deadline except urllib.error.HTTPError as e: err = json.loads(e.read().decode() or "{}").get("error", "") if err in ("authorization_pending", "slow_down"): if err == "slow_down": interval += 5 continue die("login failed: %s" % err, EXIT_AUTH) if not token: die("login timed out", EXIT_AUTH) bearer = token.get("access_token") # exchange the IdP token for an API key of ours, then make sure a warehouse exists. The ID token rides along # (X-Id-Token): the API reads when the provider signed the person in from it when the access token does not say key = _bearer_request(args, "POST", "/v1/api-keys", {"label": args.label}, bearer, headers={"X-Id-Token": token["id_token"]} if token.get("id_token") else None) _finish_login(args, key["api_key"], args.label, base={"issuer": iss.get("issuer"), "sso": getattr(args, "sso", None) or None}) def _login_client_credentials(args): """`lhbox login --client-credentials`: an unattended agent signs in as a SERVICE ACCOUNT of its organisation (platform/docs/service-accounts.md) with its application's client credentials at the organisation's identity provider. The token endpoint is read from the issuer's discovery document; a token is fetched now and shown to the API (GET /v1/orgs) before anything is saved. Saved: the issuer, the token endpoint, the client id, the scope and the NAME of the environment variable holding the secret -- never the secret, never a token. Every later command fetches its own token (kept in memory, about an hour).""" missing = [f for f, v in (("--issuer", args.issuer), ("--client-id", args.client_id), ("--client-secret-env", args.client_secret_env), ("--scope", args.scope)) if not v] if missing: die_json("missing_flag", "lhbox login --client-credentials needs %s." % ", ".join(missing), EXIT_USAGE, remedy="lhbox login --client-credentials --issuer https://login.microsoftonline.com//v2.0 " "--client-id --client-secret-env LHBOX_CLIENT_SECRET --scope api:///.default") # an API key given here would win over the saved login, and a saved key would be overwritten while still live (high # review of #1450, finding 1): refused, as `lhbox new` refuses if getattr(args, "api_key", None) or _env("API_KEY"): die_json("key_in_use", "A key is given with --api-key or LHBOX_API_KEY; it would still be the one every command " "uses, not the service account.", EXIT_USAGE, remedy="Unset LHBOX_API_KEY (and drop --api-key), then run lhbox login --client-credentials again.") if (saved_credentials().get(args.url.rstrip("/")) or {}).get("api_key"): die_json("already_connected", "This machine already holds a key for %s; signing in as a service account would " "replace it while it still works." % args.url.rstrip("/"), EXIT_USAGE, remedy="lhbox logout first (it revokes that key), or keep both: lhbox --profile login " "--client-credentials ...") issuer = args.issuer.rstrip("/") if not issuer.startswith("https://"): die_json("invalid_value", "--issuer is the identity provider's https issuer URL.", EXIT_ERROR, got=issuer[:200]) disc_url = issuer + "/.well-known/openid-configuration" try: with urllib.request.urlopen(urllib.request.Request(disc_url, headers={"Accept": "application/json"}), timeout=30) as r: disc = json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): _die_timeout("GET", disc_url, 30) except urllib.error.HTTPError as e: die_json("identity_provider_unreachable", "The issuer's discovery document answered HTTP %d." % e.code, EXIT_ERROR, url=disc_url) except urllib.error.URLError as e: _die_unreachable("GET", disc_url, e.reason) except (ValueError, *_LOST_ANSWER) as e: die_json("identity_provider_unreachable", "The issuer's discovery document could not be read (%s)." % type(e).__name__, EXIT_ERROR, url=disc_url) endpoint = disc.get("token_endpoint") if isinstance(disc, dict) else None if not endpoint or not str(endpoint).startswith("https://"): die_json("identity_provider_unreachable", "The issuer's discovery document names no https token endpoint.", EXIT_ERROR, url=disc_url) entry = {"kind": "client_credentials", "issuer": issuer, "token_endpoint": endpoint, "client_id": args.client_id, "client_secret_env": args.client_secret_env, "scope": args.scope, "client_auth": args.client_auth} token = _client_credentials_token(entry) orgs = _bearer_request(args, "GET", "/v1/orgs", None, token).get("organizations") or [] saved_to = save_credentials(args, entry, drop_pending=True) out = {"connected": True, "kind": "service_account", "organization": (orgs[0] if orgs else {}).get("handle"), "issuer": issuer, "client_id": args.client_id, "client_secret_env": args.client_secret_env, "saved_to": saved_to, "note": "Saved without the secret or a token: each command reads %s and gets a fresh token from the identity " "provider." % args.client_secret_env} if _want_json(args): print_json(out) else: print("Signed in as a service account of %s through %s. Saved to %s (no secret, no token: each command reads %s)." % (out["organization"] or "your organisation", issuer, saved_to, args.client_secret_env)) def _idp_post(url, form, poll=False): """One form POST to the identity provider. HTTPError propagates (the device flow reads authorization_pending out of it); an unreachable IdP is the network exit code, not a traceback. poll: a read timeout propagates too, so one slow poll does not end a login the person is approving.""" req = urllib.request.Request(url, data=urllib.parse.urlencode(form).encode(), method="POST") req.add_header("Content-Type", "application/x-www-form-urlencoded") try: with urllib.request.urlopen(req, timeout=30) as r: return json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): if poll: raise _die_timeout("POST", url, 30, read=True) # a device code or a token: nothing changes except urllib.error.HTTPError: raise except urllib.error.URLError as e: _die_unreachable("POST", url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url("POST", url, e) def _bearer_request(args, method, path, body, bearer, headers=None): url = args.url.rstrip("/") + path req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None, method=method) req.add_unredirected_header("Authorization", "Bearer " + bearer) req.add_header("Content-Type", "application/json") for k, v in (headers or {}).items(): req.add_header(k, v) try: with urllib.request.urlopen(req, timeout=60) as r: return json.loads(r.read().decode() or "{}") except (TimeoutError, socket.timeout): _die_timeout(method, path, 60) # POST /v1/api-keys: unknown; GET: a read except urllib.error.HTTPError as e: payload = e.read().decode() try: parsed = json.loads(payload) except ValueError: parsed = {"error": {"code": "http_%d" % e.code, "message": "%s %s -> HTTP %d: %s" % (method, path, e.code, payload[:300])}} _fail(method, path, e.code, parsed) except urllib.error.URLError as e: _die_unreachable(method, url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url(method, path, e) def cmd_apikey_create(args): emit(args, request(args, "POST", "/v1/api-keys", {"label": args.label})) def cmd_apikey_list(args): emit(args, request(args, "GET", "/v1/api-keys")["api_keys"], ["key_id", "label", "created_at", "last_used_at", "revoked_at"]) def cmd_apikey_revoke(args): _confirm_irreversible(args, "Revoke API key %s" % args.key_id) emit(args, request(args, "DELETE", "/v1/api-keys/%s" % urllib.parse.quote(args.key_id))) def cmd_org_list(args): emit(args, request(args, "GET", "/v1/orgs")["organizations"], ["name", "org_id", "role", "members", "domain_join"]) def _one_org(args): if getattr(args, "org", None): return args.org orgs = request(args, "GET", "/v1/orgs")["organizations"] if len(orgs) == 1: return orgs[0]["org_id"] die("You belong to %d organisations; pass --org (lhbox org list)." % len(orgs), EXIT_USAGE) def cmd_org_members(args): emit(args, request(args, "GET", "/v1/orgs/%s/members" % _one_org(args))["members"], ["display_name", "email", "role", "principal_id"]) def _invite_access(specs): """`--catalog NAME[:read|write]` (repeatable) -> the invitation's `access`: [{warehouse, level}], read when no level is named. A member reads no catalog until given access (2026-11-12): this is how an invitation gives it.""" access = [] for spec in specs or []: name, sep, level = spec.rpartition(":") if not sep: name, level = spec, "read" if not name or level not in ("read", "write"): die("--catalog is NAME or NAME:read|write (the catalog's name or id, then the level; read when left out): got %r." % spec, EXIT_USAGE) access.append({"warehouse": name, "level": level}) return access def cmd_org_invite(args): body = {"email": args.email, "role": args.role} access = _invite_access(getattr(args, "catalog", None)) if access: body["access"] = access out = request(args, "POST", "/v1/orgs/%s/invitations" % _one_org(args), body) if _want_json(args): print_json(out); return print("Invitation for %s as %s (%s). Give them:\n %s" % (out["email"], out["role"], "mailed" if out.get("mailed") else "not mailed: no mail server", out["accept_with"])) given = out.get("access") or [] if given: print("On joining they are given: %s." % ", ".join("%s (%s)" % (g.get("name") or g.get("warehouse_id"), g.get("level")) for g in given)) elif out.get("role") != "admin": print("The invitation gives no catalog: they will read only the catalogs open to the whole organisation, until " "someone grants them more (lhbox catalog grant).") def cmd_org_accept(args): emit(args, request(args, "POST", "/v1/orgs/invitations/accept", {"token": args.token})) def cmd_org_domain(args): org = _one_org(args) dom = urllib.parse.quote(args.domain, safe="") if args.remove: emit(args, request(args, "DELETE", "/v1/orgs/%s/domains/%s" % (org, dom))) return if args.verify: emit(args, request(args, "POST", "/v1/orgs/%s/domains/%s/verify" % (org, dom))) return out = request(args, "POST", "/v1/orgs/%s/domains" % org, {"domain": args.domain}) claim = out.get("claim") or {} if _want_json(args) or claim.get("verified"): emit(args, out); return # a claim does nothing until a DNS TXT record proves the domain is the organisation's (audit 2026-10-01, M5) if out.get("held_by_another_organisation") and out.get("note"): print(out["note"]) elif claim.get("admin_address"): # an admin's verified address on the domain is enough to offer membership (2026-11-17); DNS makes it exclusive org_flag = " --org %s" % shlex.quote(args.org) if args.org else "" print("Claimed %s. An admin's verified address is on it: `lhbox org set%s --domain-join on` offers membership to " "people there.\nTo make the domain this organisation's alone (single sign-on needs it), publish this DNS TXT " "record:\n %s TXT \"%s\"\nthen run: lhbox org domain%s --domain %s --verify" % (claim.get("domain", args.domain), org_flag, claim.get("txt_name"), claim.get("txt_value"), org_flag, args.domain)) return # the org it was run with goes into the next step: without it, a person in two organisations is refused (#2207) print("Claimed %s, not verified yet: it does nothing until it is. Publish this DNS TXT record:\n %s TXT \"%s\"\n" "then run: lhbox org domain%s --domain %s --verify" % (claim.get("domain", args.domain), claim.get("txt_name"), claim.get("txt_value"), " --org %s" % shlex.quote(args.org) if args.org else "", args.domain)) def cmd_org_join(args): org = args.org if not org: offers = request(args, "GET", "/v1/orgs").get("domain_offers") or [] if len(offers) != 1: die("%d domain offers; pass --org (lhbox org offers lists them)." % len(offers), EXIT_USAGE) org = offers[0]["handle"] or offers[0]["org_id"] emit(args, request(args, "POST", "/v1/orgs/%s/join" % urllib.parse.quote(org, safe=""))) def cmd_org_offers(args): emit(args, request(args, "GET", "/v1/orgs").get("domain_offers") or [], ["name", "handle", "domain", "role"]) def cmd_org_set(args): body = {} if args.name: body["name"] = args.name if args.domain_join is not None: body["domain_join"] = args.domain_join == "on" if getattr(args, "deprovision", None): body["deprovision"] = args.deprovision emit(args, request(args, "PATCH", "/v1/orgs/%s" % _one_org(args), body)) def cmd_org_policy(args): """`lhbox org policy`: what the organisation's members may do (platform/docs/org-policy.md); with a flag, an admin (a person, not a token) changes it. Read: one row per setting, then what you may do and whom to ask.""" body = {k: v for k, v in (("publish_catalogs", args.publish_catalogs), ("connect_agents", args.connect_agents), ("hosted_agents", args.hosted_agents), ("new_catalogs", getattr(args, "new_catalogs", None)), ("session_lifetime", getattr(args, "session_lifetime", None)), ("create_connections", getattr(args, "create_connections", None))) if v} org = _one_org(args) out = request(args, "PATCH" if body else "GET", "/v1/orgs/%s/policy" % org, body or None) if _want_json(args): print_json(out) return may = out.get("you_may") or {} # `you_may` is answered for the settings that say who may do something; new_catalogs is a default, not a permission _table([{"setting": s["key"], "who_may": s["value"], "default": s["default"], "you_may": ("yes" if may[s["key"]] else "no") if s["key"] in may else "-"} for s in out.get("settings") or []], ["setting", "who_may", "default", "you_may"]) print("\nyour role: %s; admins: %s" % (out.get("your_role"), ", ".join(out.get("admins") or []) or "-")) if out.get("public_catalogs"): print("public now: %s" % ", ".join(c["name"] for c in out["public_catalogs"])) if out.get("note"): print(out["note"]) def cmd_org_scim_token_create(args): body = {"label": args.label} if args.label else {} # the token is shown once, on purpose: it is pasted into the identity provider's provisioning settings emit(args, request(args, "POST", "/v1/orgs/%s/scim/tokens" % _one_org(args), body)) def cmd_org_scim_token_list(args): out = request(args, "GET", "/v1/orgs/%s/scim/tokens" % _one_org(args)) emit(args, out["tokens"], ["token_id", "label", "created_at", "last_used_at", "revoked_at"]) def cmd_org_scim_token_revoke(args): _confirm_irreversible(args, "Revoke SCIM token %s (the identity provider's next request is refused)" % args.token_id) emit(args, request(args, "DELETE", "/v1/orgs/%s/scim/tokens/%s" % (_one_org(args), urllib.parse.quote(args.token_id)))) # --------------------------------------------------------------------------- connections and sources (PLAN 42) _CONNECTION_COLUMNS = ["name", "type", "endpoint", "bucket", "prefix", "region", "anonymous", "owner_id", "use_access", "state", "sources"] _SOURCE_COLUMNS = ["name", "type", "location", "org_access", "your_level", "connection"] def _connection_row(c): # an Azure connection's container is its bucket column (account and tenant are in --json) # an Iceberg catalog's address is its endpoint column (its storage endpoint, warehouse and namespaces are in --json) # a BigQuery connection's project is its bucket column (its account, datasets and grants are in --json and show) return dict(c, endpoint=c.get("catalog_uri") or c.get("endpoint"), bucket=c.get("bucket") or c.get("container") or c.get("project"), sources=", ".join(c.get("sources") or []) or "-") def _source_row(s): loc = s.get("location") or {} return dict(s, location="%s/%s/%s" % (loc.get("endpoint") or "", loc.get("bucket") or "", loc.get("prefix") or ""), connection=s.get("connection") or "-") def _key_id(args): """The access key id: --access-key-id, or --access-key-id-env VAR for an agent holding it in its environment.""" env = getattr(args, "access_key_id_env", None) if env and args.access_key_id: die("Give the key id one way: --access-key-id or --access-key-id-env VAR.", EXIT_USAGE) if env: if env not in os.environ: die("The environment variable %s is not set." % env, EXIT_USAGE) return os.environ[env].strip() if not args.access_key_id: die("Give the key's id with --access-key-id or --access-key-id-env VAR.", EXIT_USAGE) return args.access_key_id def _client_secret_body(args): """An Azure connection's credential: its client secret alone (the tenant and client ids are where it points).""" if args.access_key_id or args.access_key_id_env: die("An Azure connection takes its client secret (--value / --value-env), not --access-key-id.", EXIT_USAGE) return {"client_secret": _secret_value(args, "the client secret")} def _is_azure(args): """Whether the named connection is an Azure one (rotate and take-over send its client secret alone).""" if args.access_key_id or args.access_key_id_env or not (args.value or args.value_env): return False return request(args, "GET", _connection_path(args))["connection"].get("type") == "azure_blob" _ICEBERG_FLAGS = ("catalog_uri", "warehouse", "auth", "token_path", "scope", "namespace", "catalog_secret", "catalog_secret_env", "catalog") def _catalog_secret(args, what): """An Iceberg catalog's client secret or token: --catalog-secret @FILE / @- or --catalog-secret-env VAR (never inline).""" import types return _secret_value(types.SimpleNamespace(**{**vars(args), "value": args.catalog_secret, "value_env": args.catalog_secret_env}), what) def _iceberg_connection_body(args): """--type iceberg_rest (another Iceberg REST catalog, research/145) or lakehousebox (another organisation's public catalog, by name).""" body = {"name": args.name, "type": args.type} if args.namespace: body["namespaces"] = [n.strip() for v in args.namespace for n in v.split(",") if n.strip()] if args.type == "lakehousebox": if not args.catalog: die("A LakehouseBox catalog connection needs --catalog /.", EXIT_USAGE) if any(getattr(args, f, None) for f in ("catalog_uri", "warehouse", "auth", "token_path", "scope", "client_id", "catalog_secret", "catalog_secret_env", "endpoint", "bucket", "access_key_id", "access_key_id_env", "value", "value_env")): die("A public LakehouseBox catalog takes --catalog (and --namespace) alone, no key. For a private one, use " "--type iceberg_rest with its recipe.", EXIT_USAGE) body["catalog"] = args.catalog return body if args.catalog: die("--catalog is for --type lakehousebox; an Iceberg REST catalog is --catalog-uri.", EXIT_USAGE) if not args.catalog_uri or not args.endpoint or not args.bucket: die("An Iceberg REST catalog connection needs --catalog-uri, and where its tables' files are: --endpoint and " "--bucket.", EXIT_USAGE) auth = args.auth or "oauth2" body.update(catalog_uri=args.catalog_uri, auth=auth, storage_endpoint=args.endpoint, bucket=args.bucket) if auth == "oauth2": if not args.client_id: die("--auth oauth2 needs --client-id, and its secret with --catalog-secret @FILE or --catalog-secret-env VAR.", EXIT_USAGE) body.update(client_id=args.client_id, client_secret=_catalog_secret(args, "the catalog's client secret")) elif auth == "bearer": body["token"] = _catalog_secret(args, "the catalog's token") elif args.client_id or args.catalog_secret or args.catalog_secret_env: die("--auth none (a public catalog) takes no --client-id or --catalog-secret.", EXIT_USAGE) for field in ("warehouse", "token_path", "scope", "region", "url_style"): if getattr(args, field, None) is not None: body[field] = getattr(args, field) if args.anonymous: if args.access_key_id or args.access_key_id_env or args.value or args.value_env: die("A public bucket takes no storage key: give --anonymous alone, or a key pair without it.", EXIT_USAGE) body["storage_anonymous"] = True else: body.update(access_key_id=_key_id(args), secret_access_key=_secret_value(args, "the storage key's secret")) return body _BQ_FLAGS = ("project", "billing_project", "dataset") def _bigquery_connection_body(args): """--type bigquery (research/147): the project and its datasets; LakehouseBox makes the connection's own Google service account, which the person grants. No key of theirs.""" other = [f for f in ("endpoint", "bucket", "prefix", "region", "url_style", "account", "container", "tenant_id", "client_id", "endpoint_suffix", "access_key_id", "access_key_id_env", "value", "value_env", "catalog_url", "data_url") + _ICEBERG_FLAGS if getattr(args, f, None)] if other or args.anonymous: die("A BigQuery connection takes --project (and --billing-project, --dataset) alone: no key, LakehouseBox " "makes its service account.", EXIT_USAGE) if not args.project: die("A BigQuery connection needs --project, the Google Cloud project id.", EXIT_USAGE) body = {"name": args.name, "type": "bigquery", "project": args.project} if args.billing_project: body["billing_project"] = args.billing_project if args.dataset: body["datasets"] = [d.strip() for v in args.dataset for d in v.split(",") if d.strip()] return body def _print_bq_grant(conn): """What the person grants the connection's service account, as commands they (or their agent) can run.""" grant = conn.get("grant") or {} if not grant: return print("Grant its service account read access (Google Cloud):\n %s" % grant.get("service_account"), file=sys.stderr) for cmd in grant.get("commands") or []: print(" " + cmd, file=sys.stderr) def cmd_connection_create(args): if args.type != "bigquery" and any(getattr(args, f, None) for f in _BQ_FLAGS): die("--project, --billing-project and --dataset are for --type bigquery.", EXIT_USAGE) if args.type == "bigquery": body = _bigquery_connection_body(args) elif args.type in ("iceberg_rest", "lakehousebox"): if args.account or args.container or args.tenant_id or args.endpoint_suffix or args.prefix: die("--account, --container, --tenant-id, --endpoint-suffix and --prefix are not for a catalog connection.", EXIT_USAGE) body = _iceberg_connection_body(args) elif any(getattr(args, f, None) for f in _ICEBERG_FLAGS): die("--catalog-uri, --warehouse, --auth, --token-path, --scope, --namespace, --catalog-secret and --catalog are " "for --type iceberg_rest or lakehousebox.", EXIT_USAGE) elif args.type == "portolan": if not args.catalog_url: die("A Portolan connection needs --catalog-url, the catalog's root " "(https://host/bucket/folder/catalog.json).", EXIT_USAGE) if args.endpoint or args.bucket or args.prefix or args.account or args.container or args.url_style: die("A Portolan connection takes --catalog-url (and --data-url), not --endpoint, --bucket, --prefix, " "--account, --container or --url-style.", EXIT_USAGE) body = {"name": args.name, "type": "portolan", "url": args.catalog_url} if args.data_url: body["data_url"] = args.data_url if args.region: body["region"] = args.region if args.access_key_id or args.access_key_id_env or args.value or args.value_env: body.update(anonymous=False, access_key_id=_key_id(args), secret_access_key=_secret_value(args, "the secret access key")) elif args.type == "azure_blob": given = {"--account": args.account, "--container": args.container, "--tenant-id": args.tenant_id, "--client-id": args.client_id} if any(v is None for v in given.values()): die("An Azure connection needs %s." % ", ".join(k for k, v in given.items() if v is None), EXIT_USAGE) if args.endpoint or args.bucket or args.region or args.url_style or args.anonymous: die("An Azure connection takes --account and --container, not --endpoint, --bucket, --region, --url-style " "or --anonymous.", EXIT_USAGE) body = {"name": args.name, "type": args.type, "account": args.account, "container": args.container, "tenant_id": args.tenant_id, "client_id": args.client_id, **_client_secret_body(args)} for field in ("prefix", "endpoint_suffix"): if getattr(args, field, None) is not None: body[field] = getattr(args, field) else: if args.account or args.container or args.tenant_id or args.client_id or args.endpoint_suffix: die("--account, --container, --tenant-id, --client-id and --endpoint-suffix are for --type azure_blob.", EXIT_USAGE) if not args.endpoint or not args.bucket: die("An S3 connection needs --endpoint and --bucket.", EXIT_USAGE) body = _s3_connection_body(args) out = request(args, "POST", "/v1/orgs/%s/connections" % _one_org(args), body) if _want_json(args): emit(args, out) return emit(args, [_connection_row(out["connection"])], _CONNECTION_COLUMNS) _print_bq_grant(out["connection"]) print("Attach it as a source: lhbox source attach --connection %s" % args.name, file=sys.stderr) def _s3_connection_body(args): body = {"name": args.name, "type": args.type, "endpoint": args.endpoint, "bucket": args.bucket} if args.anonymous: if args.access_key_id or args.access_key_id_env or args.value or args.value_env: die("A public bucket takes no key: give --anonymous alone, or a key pair without it.", EXIT_USAGE) body["anonymous"] = True else: body.update(access_key_id=_key_id(args), secret_access_key=_secret_value(args, "the secret access key")) for field in ("prefix", "region", "url_style"): if getattr(args, field, None) is not None: body[field] = getattr(args, field) return body def cmd_connection_list(args): out = request(args, "GET", "/v1/orgs/%s/connections" % _one_org(args)) if _want_json(args): emit(args, out) return emit(args, [_connection_row(c) for c in out.get("connections") or []], _CONNECTION_COLUMNS) def cmd_connection_show(args): out = request(args, "GET", "/v1/orgs/%s/connections/%s" % (_one_org(args), urllib.parse.quote(args.name))) emit(args, out if _want_json(args) else [_connection_row(out["connection"])], None if _want_json(args) else _CONNECTION_COLUMNS) if not _want_json(args): _print_bq_grant(out["connection"]) def _connection_key_body(args, optional=False): """What `connection rotate` and `connection take-over` send as the connection's new secret, by its type: an Iceberg catalog's client secret (or token) with its storage key pair, an Azure one's client secret, else the S3 key pair. optional (take-over): no key given is an empty body, for a connection that holds none (a public bucket).""" if args.catalog_secret or args.catalog_secret_env: # an Iceberg catalog's: its client secret (or token) and its storage key pair, replaced together conn = request(args, "GET", _connection_path(args))["connection"] if conn.get("type") != "iceberg_rest": die("--catalog-secret is for an iceberg_rest connection.", EXIT_USAGE) body = {"token" if conn.get("auth") == "bearer" else "client_secret": _catalog_secret(args, "the catalog's client secret or token")} if not conn.get("storage_anonymous"): body.update(access_key_id=_key_id(args), secret_access_key=_secret_value(args, "the storage key's secret")) return body if _is_azure(args): return _client_secret_body(args) if optional and not (args.access_key_id or args.access_key_id_env or args.value or args.value_env): return {} return {"access_key_id": _key_id(args), "secret_access_key": _secret_value(args, "the secret access key")} def cmd_connection_rotate(args): out = request(args, "PUT", "/v1/orgs/%s/connections/%s/secret" % (_one_org(args), urllib.parse.quote(args.name)), _connection_key_body(args)) emit(args, out if _want_json(args) else [_connection_row(out["connection"])], None if _want_json(args) else _CONNECTION_COLUMNS) def _connection_path(args, *rest): return "/v1/orgs/%s/connections/%s" % (_one_org(args), "/".join([urllib.parse.quote(args.name)] + list(rest))) def _share(args, use): if bool(args.everyone) == bool(args.principal): die("Say who: --everyone (every member of the organisation) or --principal (one person or token).", EXIT_USAGE) if args.everyone: out = request(args, "PUT", _connection_path(args, "use-access"), {"use_access": "everyone" if use else "owner"}) else: out = request(args, "PUT", _connection_path(args, "grants", urllib.parse.quote(args.principal)), {"level": "use" if use else "none"}) emit(args, out if _want_json(args) or "connection" not in out or not isinstance(out["connection"], dict) else [_connection_row(out["connection"])], None if _want_json(args) or not isinstance(out.get("connection"), dict) else _CONNECTION_COLUMNS) def cmd_connection_share(args): """`lhbox connection share`: let others attach sources from your connection (its owner or an admin). Reading a source stays the source's own access; sharing a connection never shares its key.""" _share(args, True) def cmd_connection_unshare(args): _share(args, False) def cmd_connection_take_over(args): """`lhbox connection take-over`: an admin makes a connection theirs with a key of their own (none for a public bucket); one stopped because its owner left works again.""" out = request(args, "POST", _connection_path(args, "take-over"), _connection_key_body(args, optional=True)) emit(args, out if _want_json(args) else [_connection_row(out["connection"])], None if _want_json(args) else _CONNECTION_COLUMNS) def cmd_connection_transfer(args): out = request(args, "PUT", _connection_path(args, "owner"), {"principal_id": args.to}) emit(args, out if _want_json(args) else [_connection_row(out["connection"])], None if _want_json(args) else _CONNECTION_COLUMNS) def cmd_connection_delete(args): _confirm_irreversible(args, "Delete connection %s (its stored key pair goes; a connection in use is refused)" % args.name) emit(args, request(args, "DELETE", "/v1/orgs/%s/connections/%s" % (_one_org(args), urllib.parse.quote(args.name)))) def cmd_source_attach(args): body = {"name": args.name, "connection": args.connection} if args.everyone: body["org_access"] = "read" out = request(args, "POST", "/v1/orgs/%s/sources" % _one_org(args), body) emit(args, out if _want_json(args) else [_source_row(out["source"])], None if _want_json(args) else _SOURCE_COLUMNS) def cmd_source_list(args): out = request(args, "GET", "/v1/orgs/%s/sources" % _one_org(args)) if _want_json(args): emit(args, out) return emit(args, [_source_row(s) for s in out.get("sources") or []], _SOURCE_COLUMNS) def cmd_source_show(args): out = request(args, "GET", "/v1/orgs/%s/sources/%s" % (_one_org(args), urllib.parse.quote(args.name))) emit(args, out if _want_json(args) else [_source_row(out["source"])], None if _want_json(args) else _SOURCE_COLUMNS) _SOURCE_TABLE_COLUMNS = ["sql_name", "format", "files", "path"] def cmd_source_tables(args): out = request(args, "GET", "/v1/orgs/%s/sources/%s/tables" % (_one_org(args), urllib.parse.quote(args.name))) emit(args, out if _want_json(args) else out.get("tables") or [], None if _want_json(args) else _SOURCE_TABLE_COLUMNS) def cmd_source_refresh(args): out = request(args, "POST", "/v1/orgs/%s/sources/%s/refresh" % (_one_org(args), urllib.parse.quote(args.name)), {}) if _want_json(args): emit(args, out) return emit(args, [dict(t, sql_name="%s.%s.%s" % (args.name, t["schema"], t["name"])) for t in out.get("tables") or []], _SOURCE_TABLE_COLUMNS) if out.get("more_files") or out.get("more_tables"): print("There were more files or tables than are kept; narrow the connection's prefix.", file=sys.stderr) def cmd_source_detach(args): _confirm_irreversible(args, "Detach source %s (its grants go; its connection stays)" % args.name) emit(args, request(args, "DELETE", "/v1/orgs/%s/sources/%s" % (_one_org(args), urllib.parse.quote(args.name)))) def cmd_source_access(args): out = request(args, "PUT", "/v1/orgs/%s/sources/%s/org-access" % (_one_org(args), urllib.parse.quote(args.name)), {"org_access": "read" if args.access == "everyone" else "none"}) emit(args, out if _want_json(args) else [_source_row(out["source"])], None if _want_json(args) else _SOURCE_COLUMNS) def _source_grant(args, level): emit(args, request(args, "PUT", "/v1/orgs/%s/sources/%s/grants/%s" % ( _one_org(args), urllib.parse.quote(args.name), urllib.parse.quote(args.principal)), {"level": level})) def cmd_source_grant(args): _source_grant(args, "read") def cmd_source_revoke(args): _source_grant(args, "none") _SERVICE_ACCOUNT_COLUMNS = ["name", "principal_id", "subject", "active", "last_used_at", "grants"] def _service_account_row(sa): return dict(sa, grants=", ".join("%s:%s" % (g.get("name") or g.get("warehouse_id"), g.get("level")) for g in sa.get("grants") or []) or "-") def cmd_org_service_account_create(args): # --google-token: a Google Cloud workload's service account, proven by an ID token of it (plane/google_workloads.py) if args.google_token is not None: proof = sys.stdin.read() if args.google_token == "-" else args.google_token if not proof.strip(): die_json("invalid_value", "--google-token is empty: give the ID token, or - to read it from stdin.", EXIT_USAGE) body = {"issuer": "google", "proof": proof.strip()} else: body = {"subject": args.subject} if args.description is not None: body["description"] = args.description out = request(args, "PUT", "/v1/orgs/%s/service-accounts/%s" % (_one_org(args), urllib.parse.quote(args.name)), body) if _want_json(args): emit(args, out) return emit(args, [_service_account_row(out["service_account"])], _SERVICE_ACCOUNT_COLUMNS) print(out.get("note") or "", file=sys.stderr) def cmd_org_service_account_list(args): out = request(args, "GET", "/v1/orgs/%s/service-accounts" % _one_org(args)) if _want_json(args): emit(args, out) return emit(args, [_service_account_row(sa) for sa in out.get("service_accounts") or []], _SERVICE_ACCOUNT_COLUMNS) def cmd_org_service_account_delete(args): _confirm_irreversible(args, "Delete service account %s (its next request is refused, its grants go)" % args.name) emit(args, request(args, "DELETE", "/v1/orgs/%s/service-accounts/%s" % (_one_org(args), urllib.parse.quote(args.name)))) def _group_rules_file(path): """The rule set of `lhbox org group-rules set --file`: a JSON file (or - for stdin) holding {"rules": [...]} or the list itself. A file that cannot be read or parsed is one envelope, nothing sent.""" try: raw = _news_body(path) # the file or stdin; an unreadable file is already one envelope except UnicodeDecodeError as exc: die_json("file_error", "%s is not UTF-8 text: %s" % (path, exc.reason), EXIT_USAGE, path=path) try: data = json.loads(raw) except ValueError as exc: die_json("invalid_json", "%s is not JSON: %s" % (path, exc), EXIT_ERROR, path=path) if isinstance(data, list): data = {"rules": data} if not isinstance(data, dict) or not isinstance(data.get("rules"), list): die_json("invalid_value", "The file holds {\"rules\": [...]} (or the list of rules itself).", EXIT_ERROR, path=path) return {"rules": data["rules"]} _GROUP_RULE_COLUMNS = ["rule_id", "group_name", "kind", "role", "catalog", "namespace", "level", "members"] def cmd_org_group_rules_set(args): body = _group_rules_file(args.file) out = request(args, "PUT", "/v1/orgs/%s/group-rules" % _one_org(args), body) if _want_json(args): emit(args, out) return ch = out.get("changes") or {} emit(args, out.get("rules") or [], _GROUP_RULE_COLUMNS) # narrowed: a membership read withdrawn on a catalog the rules partition; widened: that withdrawal lifted print("%d rule(s)%s; %d person(s) changed: %d granted, %d revoked, %d narrowed, %d widened, %d promoted, %d demoted" % (len(out.get("rules") or []), "" if out.get("rules_changed") else " (unchanged)", ch.get("people", 0), len(ch.get("granted") or []), len(ch.get("revoked") or []), len(ch.get("narrowed") or []), len(ch.get("widened") or []), len(ch.get("promoted") or []), len(ch.get("demoted") or [])), file=sys.stderr) if out.get("shadowed"): print("note: %d namespace level(s) do not apply (the person holds a lower level on the whole catalog): %s" % (len(out["shadowed"]), out.get("shadowed_note") or ""), file=sys.stderr) for key, what in (("unknown_groups", "group(s) not provisioned yet"), ("unknown_namespaces", "namespace(s) not created yet")): if out.get(key): print("note: %s: %s" % (what, json.dumps(out[key])), file=sys.stderr) def cmd_org_group_rules_list(args): out = request(args, "GET", "/v1/orgs/%s/group-rules" % _one_org(args)) if _want_json(args): emit(args, out) return emit(args, out.get("rules") or [], _GROUP_RULE_COLUMNS) def cmd_org_group_rules_clear(args): _confirm_irreversible(args, "Remove every group rule of the organisation (what they gave is revoked; hand-made grants stay)") emit(args, request(args, "DELETE", "/v1/orgs/%s/group-rules" % _one_org(args))) def cmd_org_role(args): emit(args, request(args, "PATCH", "/v1/orgs/%s/members/%s" % (_one_org(args), args.principal), {"role": args.role})) # --------------------------------------------------------------------------- operator: plans and limits # `lhbox admin ...` (docs/audit-and-quota.md, "Plans and per-organisation limits"): the operator's commands, run by an # agent. The bearer is the OPERATOR key from LHBOX_OPERATOR_KEY alone -- never the saved agent key, never LHBOX_API_KEY -- # and the API answers 404 for /v1/admin/* on a deployment without AL_OPERATOR_KEY. ADMIN_LIMIT_FLAGS = (("storage_gb", "storage_bytes"), ("public_storage_gb", "public_storage_bytes"), ("objects", "objects"), ("catalogs", "warehouses"), ("projects", "projects"), # scheduled SQL sinks (research/46): the feature (0 = not enabled) and its per-organisation budget ("sql_sinks", "sql_sinks"), ("sql_min_every", "sql_min_every_seconds"), ("sql_run_seconds", "sql_run_seconds"), ("sql_requests_per_run", "sql_requests_per_run"), ("sql_download_mb_per_run", "sql_download_mb_per_run")) _BYTES_LIMITS = ("storage_bytes", "public_storage_bytes") # the plan features that are a switch (0 = off, 1 = on), the only names --feature accepts on/off for ADMIN_SWITCHES = ("public_images", "enterprise") def operator_key(args): key = _env("OPERATOR_KEY") if not key: die("No operator key. `lhbox admin` reads LHBOX_OPERATOR_KEY (the deployment's AL_OPERATOR_KEY); the agent key " "and the credentials file are never used here.", EXIT_AUTH) return key def _admin(args, method, path, body=None): return request(args, method, path, body, bearer=operator_key(args)) def _plans_and_limits(args, method, path, body=None): """/v1/admin/ with the operator key, or, with --login EMAIL, the back office's /v1/backoffice/ as that install administrator: the same plans and limits either way (feedback 2026-10-16, item 5: an administrator could create an organisation with their own login and not read its limits).""" if getattr(args, "login", None): return _bo(args, method, "/v1/backoffice" + path, body) return _admin(args, method, "/v1/admin" + path, body) def _fmt_limit(name, value): return fmt_bytes(value) if name in _BYTES_LIMITS else str(value) def _limits_rows(view): """One row per limit: the effective value, where it comes from (the plan, or an operator's override), enforced.""" detail = view.get("limits_detail") or {} return [{"limit": k, "value": _fmt_limit(k, v), "source": "override" if k in (view.get("overrides") or {}) else "plan %s" % view.get("plan"), "enforced": "yes" if (detail.get(k) or {}).get("enforced") else "no"} for k, v in (view.get("limits") or {}).items()] def _audit_lines(events): for e in events or []: yield "%s %s %s -> %s%s" % (e.get("at"), e.get("actor"), json.dumps(e.get("before")), json.dumps(e.get("after")), (" (%s)" % e["note"]) if e.get("note") else "") def _emit_limits_view(args, view): if _want_json(args): emit(args, view) return print("organisation %s (%s%s)" % (view.get("name"), view.get("org_id"), ("; handle " + view["handle"]) if view.get("handle") else "")) print("plan %s%s" % (view.get("plan"), (" note: %s" % view["note"]) if view.get("note") else "")) if view.get("updated_at"): print("updated %s by %s" % (view["updated_at"], view.get("updated_by"))) if "changed" in view: print("changed %s%s" % ("yes" if view["changed"] else "no (already so)", "; bucket quotas re-set now, the store flips the buckets within about a minute" if view.get("bucket_quotas") else "")) print() _table(_limits_rows(view), ["limit", "value", "source", "enforced"]) lines = list(_audit_lines(view.get("audit"))) if lines: print("\nlast changes (newest first):") for line in lines: print(" " + line) def cmd_admin_plans(args): out = _plans_and_limits(args, "GET", "/plans") if _want_json(args): emit(args, out) return plans = out.get("plans") or {} fields = out.get("fields") or list(next(iter(plans.values()), {})) rows = [{"limit": f, **{name: _fmt_limit(f, plans[name].get(f)) for name in plans}} for f in fields] print("plans: %s (default %s)\n" % (", ".join(plans), out.get("default_plan"))) _table(rows, ["limit"] + list(plans)) def cmd_admin_org_limits(args): _emit_limits_view(args, _plans_and_limits(args, "GET", "/orgs/%s/limits" % urllib.parse.quote(args.org, safe=""))) def cmd_admin_org_set(args): overrides = {} for flag, field in ADMIN_LIMIT_FLAGS: v = getattr(args, flag) if v is None: continue if v < 0: die_json("invalid_value", "--%s must not be negative." % flag.replace("_", "-"), EXIT_USAGE, field=field, got=v) overrides[field] = int(round(v * 1000 ** 3)) if flag.endswith("_gb") else int(v) for spec in getattr(args, "feature", None) or []: field, value = _feature_override(spec) overrides[field] = value for field in args.clear or []: # the name is the API's to check (400 unknown_limit lists them): a list here goes stale, and an older lhbox would # refuse a limit a newer API has (high review of #1512, 4) overrides[field] = None body = {} if args.plan: body["plan"] = args.plan if overrides: body["overrides"] = overrides if args.note: body["note"] = args.note if "plan" not in body and "overrides" not in body: die_json("nothing_to_change", "Pass --plan, a limit flag, --feature NAME=VALUE, or --clear FIELD.", EXIT_USAGE, flags=["--plan", "--feature", "--storage-gb", "--public-storage-gb", "--objects", "--catalogs", "--projects", "--sql-sinks", "--sql-min-every", "--sql-run-seconds", "--sql-requests-per-run", "--sql-download-mb-per-run", "--clear"]) _emit_limits_view(args, _plans_and_limits(args, "PATCH", "/orgs/%s/limits" % urllib.parse.quote(args.org, safe=""), body)) def _feature_override(spec): """--feature NAME=VALUE -> (NAME, int): on/yes/true = 1, off/no/false = 0, or a non-negative count. Any limit the plan registry names (lhbox admin plans), e.g. public_images=on; the API refuses a name it does not know, listing them.""" name, sep, raw = (spec or "").partition("=") name, raw = name.strip(), raw.strip().lower() words = {"on": 1, "yes": 1, "true": 1, "off": 0, "no": 0, "false": 0} if not sep or not name or not (raw in words or raw.isdigit()): die_json("invalid_value", "--feature takes NAME=on|off|N (e.g. public_images=on); got %r." % spec, EXIT_USAGE, field="feature", got=spec, remedy="lhbox admin plans lists every name; lhbox admin org limits shows the values.") if name in _BYTES_LIMITS: # 5 here would be 5 bytes, and `on` one byte: an organisation read-only at the next quota pass (review, 1) die_json("use_the_limit_flag", "%s is a size in bytes; set it with --%s (decimal GB)." % (name, name.replace("_bytes", "_gb").replace("_", "-")), EXIT_USAGE, field=name, got=spec) if raw in words and name not in ADMIN_SWITCHES: # on/off is a feature's switch; a count limit set to `on` would become 1 (one catalog, one object) die_json("not_a_switch", "%s is a count, not an on/off feature: pass a number (%s=N)." % (name, name), EXIT_USAGE, field=name, got=spec, switches=list(ADMIN_SWITCHES)) return name, words[raw] if raw in words else int(raw) # `lhbox admin status | setup` (platform/docs/self-hosting.md "Administering an install"): a self-hosted install's # administration for scripts and hosts without a browser. Who may run what: # setup the one-time setup token `./al setup-link` printed on the host (no other credential: the install has no # administrator yet) # status an install administrator's own login (--login EMAIL: password and authenticator code asked on the terminal, a # session of a few minutes ended after the command, nothing saved) or the operator key (LHBOX_OPERATOR_KEY), for # automation. Never the saved agent key or LHBOX_API_KEY: the back office refuses API keys by design. def _ask_secret(prompt): import getpass return getpass.getpass(prompt, stream=sys.stderr) def _backoffice_login(args): """(bearer, end): --login EMAIL signs the install administrator in for this one command (password and the current authenticator code, from the terminal), and `end()` logs that session out; without --login, the operator key.""" email = getattr(args, "login", None) if not email: return operator_key(args), (lambda: None) if not sys.stdin.isatty(): die("--login asks for your password and authenticator code on a terminal; for scripts use LHBOX_OPERATOR_KEY.", EXIT_USAGE) password = _ask_secret("Password for %s (hidden): " % email) code = _ask("Authenticator code: ").strip().replace(" ", "") out = unauth_request(args, "POST", "/v1/auth/login", {"email": email, "password": password, "code": code}) token = out.get("access_token") if not token: die("The login answered no session (%s)." % ", ".join(sorted(out)), EXIT_AUTH) return token, (lambda: _logout_quietly(args, token)) def _logout_quietly(args, token): """End the --login session after the command: best effort and silent (the access token dies within 15 minutes anyway), so a logout that fails never adds an envelope to a command that succeeded (high review of #1458).""" try: req = urllib.request.Request(args.url.rstrip("/") + "/v1/auth/logout", data=b"{}", method="POST") req.add_unredirected_header("Authorization", "Bearer " + token) req.add_header("Content-Type", "application/json") with urllib.request.urlopen(req, timeout=15) as resp: resp.read() except Exception: # noqa: BLE001 -- best effort, by design pass def _bo(args, method, path, body=None): bearer, end = _backoffice_login(args) try: return request(args, method, path, body, bearer=bearer) finally: end() def _yes_no(v): return "yes" if v is True else "no" if v is False else "unknown" def cmd_admin_status(args): """The back office's Install view as text (or JSON): release, security settings and where each is set, sign-in and SCIM, the SIEM export, the last backups, storage, the install administrators. Read-only.""" v = _bo(args, "GET", "/v1/backoffice/install") if _want_json(args): emit(args, v) return r = v.get("release") or {} print("deployment %s" % v.get("deployment")) print("release %s" % ("%s (%s), signed: %s%s" % (r.get("version"), r.get("commit"), _yes_no(r.get("signed")), ", key %s" % r["key_fingerprint"] if r.get("key_fingerprint") else "") if r.get("version") else "not recorded (%s)" % (r.get("note") or ""))) sec = v.get("security") or {} print("profile %s" % (sec.get("profile") or "none")) idn = v.get("identity") or {} print("sign-in password login %s; identity providers: %s" % ( "on" if idn.get("password_login") else "off", ", ".join("%s%s" % (i["issuer"], " (second factor: provider)" if i.get("second_factor") else "") for i in idn.get("issuers") or []) or "none")) sc = idn.get("scim") or {} print("SCIM %s organisation(s), %s token(s), %s people from a directory" % (sc.get("organizations"), sc.get("tokens"), sc.get("managed_people"))) ex = v.get("audit_export") or {} if ex.get("enabled"): for name, st in sorted((ex.get("sinks") or {}).items()): print("SIEM %-9s %s sent, %s dropped, %s failed%s" % (name, st.get("sent"), st.get("dropped"), st.get("failed"), "; last error: %s" % st["last_error"] if st.get("last_error") else "")) else: print("SIEM off (AL_AUDIT_EXPORT)") b = v.get("backups") or {} for k in ("state", "store"): x = b.get(k) print("backup %-7s %s" % (k, "off, or not run yet" if not x else "last good %s%s" % ( x.get("last_ok_at") or "never", "; last error: %s" % x["last_error"] if x.get("last_error") else ""))) st = v.get("storage") or {} print("storage %s in %s catalogs" % (fmt_bytes(st.get("bytes") or 0), st.get("catalogs"))) adm = (v.get("admins") or {}) print("administrators %s" % (", ".join("%s%s" % (a.get("email") or a.get("principal_id"), "" if a.get("mfa") else " (no two-factor)") for a in adm.get("granted") or []) or "none granted")) print() rows = [{"setting": x["env"], "value": x["value"], "where": x["where"], "ENS": "" if x.get("ens") is None else ("ok" if x.get("matches_ens") else "differs: %s" % x["ens"])} for x in sec.get("settings") or []] _table(rows, ["setting", "value", "where", "ENS"]) if sec.get("note"): print("\n" + sec["note"]) def cmd_admin_setup(args): """A self-hosted install's first-run setup without a browser: the install administrator and the first organisation, with the one-time token `./al setup-link` printed. With a password, then (on a terminal) the authenticator app.""" body = {"token": args.token, "email": args.email, "display_name": args.name, "organization": {"name": args.org}} if args.handle: body["organization"]["handle"] = args.handle if args.password_stdin: body["password"] = sys.stdin.readline().rstrip("\n") elif not args.no_password: if not sys.stdin.isatty(): die("Pass --password-stdin (the password on standard input) or --no-password (the identity provider signs you in).", EXIT_USAGE) pw = _ask_secret("Choose a password (at least 12 characters, hidden): ") if pw != _ask_secret("Again: "): die("The two passwords differ.", EXIT_USAGE) body["password"] = pw out = unauth_request(args, "POST", "/v1/setup", body) enrol = out.pop("enrol_token", None) if _want_json(args): emit(args, {**out, "enrolment": "pending" if enrol else None}) return org = out.get("organization") or {} print("install administrator %s" % out.get("email")) print("organisation %s (%s), you are its admin" % (org.get("name"), org.get("handle"))) if not enrol: print("\n" + (out.get("next") or "")) return if not sys.stdin.isatty(): print("\nNext: log in at %s/app/ and turn on two-factor authentication (the back office needs it)." % site_url(args)) return st = unauth_request(args, "POST", "/v1/auth/mfa/enrol/start", {"enrol_token": enrol}) print("\nAdd this account to an authenticator app (the back office needs it):") print(" secret %s" % st.get("secret")) print(" or URI %s" % st.get("otpauth_uri")) code = _ask("Code the app shows now: ").strip().replace(" ", "") done = unauth_request(args, "POST", "/v1/auth/mfa/enrol/confirm", {"enrol_token": enrol, "code": code}) print("\nTwo-factor is on. Backup codes, each signs you in once without the phone (shown only now):") for c in done.get("backup_codes") or []: print(" " + c) if done.get("access_token"): _logout_quietly(args, done["access_token"]) print("\nLog in at %s/app/ and open the back office (/app/admin), or run `lhbox admin status --login %s`." % (site_url(args), out.get("email"))) # `lhbox admin org create|list|admin add|remove`, `lhbox admin person suspend|reactivate|revoke-all`, `lhbox admin client # add|list|disable|enable|remove` (platform/docs/self-hosting.md "Administering an install"): an install administrator's # work for scripts. Credential: --login EMAIL (their own password and code, a short session) or LHBOX_OPERATOR_KEY. def _q(v): return urllib.parse.quote(v, safe="") def _emit_admin_grant(args, out): if _want_json(args): emit(args, out) return a = out.get("admin") or {} if out.get("handle") and "name" in out: print("organisation %s (%s) %s" % (out.get("name"), out.get("handle"), out.get("org_id"))) if a.get("how") == "member": print("admin %s, an admin now%s" % (a.get("email"), " (was %s)" % a["previous_role"] if a.get("previous_role") else "")) elif a.get("how") == "invitation": print("admin %s, invited as admin (%s)" % (a.get("email"), "mailed" if a.get("mailed") else "NOT mailed: pass the link on")) print("link %s (shown once)" % a.get("accept_url")) def cmd_admin_org_create(args): body = {"name": args.name or args.handle, "handle": args.handle, "admin_email": args.admin} _emit_admin_grant(args, _bo(args, "POST", "/v1/backoffice/orgs", body)) def cmd_admin_org_list(args): qs = "?limit=%d" % args.limit + ("&q=" + _q(args.q) if args.q else "") out = _bo(args, "GET", "/v1/backoffice/orgs" + qs) if _want_json(args): emit(args, out) return _table([{"handle": o.get("handle"), "name": o.get("name"), "status": o.get("status"), "members": o.get("members"), "catalogs": o.get("catalogs"), "stored": fmt_bytes(o.get("bytes") or 0), "org_id": o.get("org_id")} for o in out.get("organizations") or []], ["handle", "name", "status", "members", "catalogs", "stored", "org_id"]) print("\n%s of %s" % (out.get("count"), out.get("total"))) def cmd_admin_org_admin_add(args): _emit_admin_grant(args, _bo(args, "PUT", "/v1/backoffice/orgs/%s/admins/%s" % (_q(args.org), _q(args.email)))) def cmd_admin_org_admin_remove(args): out = _bo(args, "DELETE", "/v1/backoffice/orgs/%s/admins/%s" % (_q(args.org), _q(args.member))) if _want_json(args): emit(args, out) elif out.get("withdrawn_invitation"): print("withdrew the admin invitation of %s" % out["withdrawn_invitation"]) else: print("%s is a member of %s now (no longer an admin)" % (args.member, args.org)) def cmd_admin_person(args): if args.action == "revoke-all": _confirm_irreversible(args, "Revoke every session, API key and token of %s" % args.person) path = {"suspend": "suspend", "reactivate": "reactivate", "revoke-all": "revoke"}[args.action] body = {"reason": args.reason} if args.action == "suspend" and args.reason else {} out = _bo(args, "POST", "/v1/backoffice/principals/%s/%s" % (_q(args.person), path), body) if _want_json(args): emit(args, out) elif args.action == "revoke-all": print("revoked: %s API key(s), %s session(s), %s token(s); %s catalog key rotation(s) queued" % ( out.get("api_keys_revoked"), out.get("sessions_revoked"), out.get("tokens_revoked"), out.get("keys_rotated"))) else: print("%s: %s%s" % (args.person, "suspended" if out.get("suspended") else "active", "" if out.get("changed") else " (already so)")) def cmd_admin_client_add(args): body = {"client_name": args.name, "redirect_uris": args.redirect_uri, "confidential": bool(args.confidential)} if args.client_id: body["client_id"] = args.client_id if args.client_uri: body["client_uri"] = args.client_uri out = _bo(args, "POST", "/v1/backoffice/oauth-clients", body) if _want_json(args): emit(args, out) return print("client_id %s (%s)" % (out.get("client_id"), out.get("type"))) if out.get("client_secret"): print("client_secret %s (shown once: store it in the client now)" % out["client_secret"]) def cmd_admin_client_list(args): out = _bo(args, "GET", "/v1/backoffice/oauth-clients" + ("?all=1" if args.all else "")) if _want_json(args): emit(args, out) return print("dynamic registration: %s; %s self-registered client(s)%s\n" % ( "on (AL_OAUTH_ALLOW_DCR)" if out.get("dynamic_registration") else "off", out.get("dynamic_count", 0), "" if args.all else " (--all lists them)")) _table([{"client_id": c["client_id"], "name": c["client_name"], "type": c["type"], "registration": c["registration"], "disabled": "yes" if c.get("disabled") else "", "connections": c.get("connections"), "redirect": " ".join(c.get("redirect_uris") or [])} for c in out.get("clients") or []], ["client_id", "name", "type", "registration", "disabled", "connections", "redirect"]) def cmd_admin_client_toggle(args): out = _bo(args, "POST", "/v1/backoffice/oauth-clients/%s/%s" % (_q(args.client_id), args.action)) if _want_json(args): emit(args, out) else: print("%s: %s" % (args.client_id, "disabled" if out.get("disabled") else "enabled")) def cmd_admin_client_remove(args): _confirm_irreversible(args, "Remove the client %s and revoke every connection made through it" % args.client_id) out = _bo(args, "DELETE", "/v1/backoffice/oauth-clients/%s" % _q(args.client_id)) if _want_json(args): emit(args, out) else: print("removed %s; %s connection(s) revoked" % (args.client_id, out.get("connections_revoked"))) # `lhbox admin news ...` (platform/docs/news.md): the product-news mailing list. Write an issue in Markdown (a draft from # the changelog: python3 platform/scripts/changelog.py --since --newsletter), send a test to yourself, then send it. def _news_body(path): if path == "-": return sys.stdin.read() try: with open(path, encoding="utf-8") as f: return f.read() except OSError as exc: die_json("file_error", "Cannot read %s: %s" % (path, exc.strerror or exc), EXIT_USAGE, path=path) def _emit_news_issue(args, out): if _want_json(args): emit(args, out) return d = out.get("deliveries") or {} print("issue %s (%s)" % (out.get("issue_id"), out.get("state"))) print("subject %s" % out.get("subject")) print("tested %s" % (out.get("tested_at") or "no: lhbox admin news test %s --to " % out.get("issue_id"))) if out.get("send_started_at"): print("sent %s sent, %s queued, %s skipped, %s failed" % (d.get("sent", 0), d.get("queued", 0), d.get("skipped", 0), d.get("failed", 0))) if out.get("sent_to"): print("test to %s%s" % (out["sent_to"], "" if out.get("footer_set") else " (the legal footer is not set: the real send will refuse)")) def cmd_admin_news_status(args): out = _admin(args, "GET", "/v1/admin/news") if _want_json(args): emit(args, out) return snd = out.get("sender") or {} print("list %s" % ("on" if out.get("enabled") else "off (AL_NEWS_ENABLED)")) print("subscribers %s" % out.get("subscribers")) print("withdrawn %s" % (", ".join("%s %s" % (k, v) for k, v in (out.get("withdrawn") or {}).items()) or "none")) print("sender %s relay %s, footer %s, webhook %s" % (snd.get("from"), "yes" if snd.get("relay_configured") else "NO", "yes" if snd.get("footer_set") else "NO", "yes" if snd.get("webhook_configured") else "no")) issues = out.get("issues") or [] if issues: print() _table([{"issue_id": i["issue_id"], "state": i["state"], "created": (i.get("created_at") or "")[:16], "sent": (i.get("deliveries") or {}).get("sent", 0), "subject": i["subject"]} for i in issues], ["issue_id", "state", "created", "sent", "subject"]) def cmd_admin_news_create(args): _emit_news_issue(args, _admin(args, "POST", "/v1/admin/news/issues", {"subject": args.subject, "body_md": _news_body(args.file)})) def cmd_admin_news_show(args): out = _admin(args, "GET", "/v1/admin/news/issues/%s" % urllib.parse.quote(args.issue, safe="")) _emit_news_issue(args, out) if not _want_json(args): print("\n" + (out.get("body_md") or "")) def cmd_admin_news_edit(args): body = {} if args.subject: body["subject"] = args.subject if args.file: body["body_md"] = _news_body(args.file) if not body: die_json("nothing_to_change", "Pass --subject and/or --file.", EXIT_USAGE) _emit_news_issue(args, _admin(args, "PATCH", "/v1/admin/news/issues/%s" % urllib.parse.quote(args.issue, safe=""), body)) def cmd_admin_news_test(args): _emit_news_issue(args, _admin(args, "POST", "/v1/admin/news/issues/%s/test" % urllib.parse.quote(args.issue, safe=""), {"to": args.to})) def cmd_admin_news_send(args): body = {"confirm": args.issue} if args.retry_failed: body["retry_failed"] = True out = _admin(args, "POST", "/v1/admin/news/issues/%s/send" % urllib.parse.quote(args.issue, safe=""), body) if _want_json(args): emit(args, out) return if out.get("resumed"): print("resumed issue %s: %s queued (%s put back in line); progress: lhbox admin news show %s" % (out.get("issue_id"), out.get("queued"), out.get("requeued", 0), out.get("issue_id"))) return print("sending issue %s to %s subscriber(s) in the background; progress: lhbox admin news show %s" % (out.get("issue_id"), out.get("recipients"), out.get("issue_id"))) def cmd_recover(args): """Retired 2026-10-01: an emailed code no longer mints a key with a person's full access (POST /v1/recover/* answers 410 recovery_retired). Says how to get back in, sends nothing, exits 1.""" site = site_url(args) message = "Recovering an API key by email is retired: an emailed code no longer mints a key with a person's full access." remedy = ("A person: reset the password at %s/app/forgot, then log in at %s/app/. A machine: run `lhbox login` " "again and approve the connection in the browser." % (site, site)) if _json_mode(): die_json("recovery_retired", message, exit_code_for(410, "recovery_retired"), reset_url=site + "/app/forgot", login_command="lhbox login", remedy=remedy) print("%s\n -> %s" % (message, remedy), file=sys.stderr) sys.exit(exit_code_for(410, "recovery_retired")) def catalog_id_of(args, ref, rows=None): """A catalog named on the command line -> its warehouse_id: an id passes through, a NAME is looked up in the catalogs the caller can see (2026-09-21: `token create --grant climate:read` reached the API as a name and was refused with warehouse_not_found). Not found: exit 4 with the list; two of that name: exit 1 naming the ids.""" if UUID_RE.match(ref or ""): return ref rows = _all_warehouses(args) if rows is None else rows hits = [w for w in rows if w.get("name") == ref] if len(hits) == 1: return _cid(hits[0]) if not hits: die_json("catalog_not_found", "No catalog named %r among the %d you can see." % (ref, len(rows)), EXIT_NOTFOUND, catalog=ref, visible=[{"name": w.get("name"), "warehouse_id": _cid(w)} for w in rows], remedy="Name one of them (lhbox catalog list shows names and ids), or its id.") die_json("ambiguous_name", "The name %r matches %d catalogs; use the id." % (ref, len(hits)), EXIT_ERROR, catalog=ref, ids=[_cid(w) for w in hits], remedy="Pass the catalog id (lhbox catalog list).") def _cid(d): """A catalog's id in an API answer: `catalog_id` since the catalog aliases (docs/rename-plan.md §6 step 1, #439), else the `warehouse_id` it twins.""" return (d or {}).get("catalog_id") or (d or {}).get("warehouse_id") def parse_grants(specs, args=None): """`--grant :` (repeatable; the catalog by name or by id) -> [{warehouse_id, level}]; names are resolved here, once, against the catalogs the caller can see.""" out = [] rows = None for spec in specs or []: ref, sep, level = spec.rpartition(":") if not sep or not ref or level not in ("read", "write"): die("--grant wants :, got %r" % spec, EXIT_USAGE) if args is not None and not UUID_RE.match(ref): if rows is None: rows = _all_warehouses(args) ref = catalog_id_of(args, ref, rows) out.append({"catalog_id": ref, "level": level}) return out def _token_body(args): body = {} if getattr(args, "name", None): body["name"] = args.name if getattr(args, "role", None): body["role"] = args.role grants = parse_grants(args.grant, args) # --warehouse is the pre-contract confinement flag: kept for one version as a write grant for wid in (getattr(args, "warehouse", None) or []): grants.append({"catalog_id": catalog_id_of(args, wid), "level": "write"}) if args.grant or getattr(args, "warehouse", None): body["grants"] = grants if getattr(args, "send", None) is not None: # a sink by id or by name (GET /v1/sinks/{ref} resolves either); `--send ""` alone clears them on update body["sinks"] = [request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(ref))["sink_id"] for ref in args.send if ref] return body def normalise_grants(raw): """Whatever shape the API answered a token's grants in -> [{catalog, level, warehouse_id}] (catalog = the NAME). Seen: a list of {warehouse_id, name, level} (create), a string "climate:read, sales:write" (list, 2026-09-21), a list of "name:level" strings, None.""" if not raw: return [] if isinstance(raw, str): raw = [p.strip() for p in raw.split(",") if p.strip()] out = [] for g in raw: if isinstance(g, dict): wid = _cid(g) out.append({"catalog": g.get("name") or g.get("catalog") or wid, "level": g.get("level"), "warehouse_id": wid}) elif isinstance(g, str): name, sep, level = g.rpartition(":") if not sep: name, level = g, None out.append({"catalog": name, "level": level, "warehouse_id": name if UUID_RE.match(name) else None}) return out def _grants_line(grants): return ", ".join("%s:%s" % (g["catalog"], g["level"]) for g in grants) def _grants_text(out): grants = normalise_grants(out.get("grants")) if not grants: text = "no catalog until granted" else: text = "grants: " + _grants_line(grants) sinks = out.get("sinks") or [] if sinks: text += "; sends to " + ", ".join("%s.%s" % (sk.get("catalog"), sk.get("name")) for sk in sinks) return text def cmd_token_create(args): body = _token_body(args) body.setdefault("grants", []) out = request(args, "POST", "/v1/orgs/%s/tokens" % _one_org(args), body) out["grants"] = normalise_grants(out.get("grants")) if _want_json(args): print_json(out); return print("Token %s created (%s of the organisation; %s). Its API key, shown once:\n %s\nGive it to the agent or program as LHBOX_API_KEY." % (out["name"], out.get("role") or "member", _grants_text(out), out["api_key"])) if out.get("deprecation"): print("note: " + out["deprecation"], file=sys.stderr) def cmd_token_update(args): ref = token_ref(args, "update") body = _token_body(args) if not body: die("Give --name, --role, one or more --grant : and/or --send (each list replaces the current one).", EXIT_USAGE) out = request(args, "PATCH", "/v1/orgs/%s/tokens/%s" % (_one_org(args), urllib.parse.quote(ref)), body) if "grants" in out: out["grants"] = normalise_grants(out.get("grants")) emit(args, out) def cmd_token_list(args): rows = request(args, "GET", "/v1/orgs/%s/tokens" % _one_org(args))["tokens"] for r in rows: # one shape in JSON, the same as `token create` answers; a legacy token (from before grants) says so r["grants"] = normalise_grants(r.get("grants")) r["legacy"] = r.get("warehouses") is None if _want_json(args): print_json(rows) return for r in rows: # the terminal shows the creator's name; JSON keeps created_by the principal_id, as `token create` answers (#2990) r["created_by"] = r.get("created_by_display") or r.get("created_by") # an MCP connection approved for all catalogs holds no grant rows: `all_catalogs` names its level (#2208) # a member's view drops the grants on catalogs it cannot read and counts them (#2366): never "none" for those hidden = r.get("grants_hidden") or 0 shown = _grants_line(r["grants"]) if hidden: r["grants"] = "%s, +%d hidden" % (shown, hidden) if shown else "%d not visible to you" % hidden else: r["grants"] = (shown or ("all (legacy)" if r["legacy"] else None) or ("all catalogs (%s)" % r["all_catalogs"] if r.get("all_catalogs") else "none")) emit(args, rows, ["name", "token_id", "role", "grants", "created_by", "last_used_at", "suspended"]) def token_ref(args, verb): """The token named on the command line: the positional `` (its name or id; research/36 §6.1: a script's `lhbox agent revoke ` -- now `lhbox token revoke` -- failed on the required flag), else `--token` / `--token-id`. Both and different, or neither: a usage error, before any request.""" pos, flag = getattr(args, "token_arg", None), getattr(args, "token_id", None) # the hidden `--confirm/--yes [NAME]` takes an optional value: `revoke --yes bot` hands "bot" to it (review of #429) yes = getattr(args, "confirm", None) yes = yes if isinstance(yes, str) else None named = {n for n in (pos, flag, yes) if n} if len(named) > 1: die("Two tokens named: %s. Name one." % " and ".join(repr(n) for n in sorted(named)), EXIT_USAGE) pos = pos or yes if not (pos or flag): die("Name the token: lhbox token %s (or its id; lhbox token list shows both), or --token ." % verb, EXIT_USAGE) return pos or flag def cmd_token_revoke(args): ref = token_ref(args, "revoke") _confirm_irreversible(args, "Revoke token %s (its key is refused at once)" % ref) emit(args, request(args, "DELETE", "/v1/orgs/%s/tokens/%s" % (_one_org(args), urllib.parse.quote(ref)))) def cmd_terms(args): if not args.accept: emit(args, request(args, "GET", "/v1/terms")) return status, body = request_status(args, "POST", "/v1/terms/accept", {}) err = (body.get("error") or {}) if isinstance(body, dict) else {} if status == 403 and err.get("code") == "not_a_person": # Terms are a person's (2026-09-20 night): a token has nothing to accept, so this is not a failure of # the command, it is the answer -- said plainly, exit 0, nothing to retry if _want_json(args): print_json({"accepted": False, "reason": "not_a_person", "kind": err.get("kind"), "message": err.get("message"), "remedy": err.get("remedy")}) else: print("Nothing to do: %s %s" % (err.get("message") or "this credential is a token.", err.get("remedy") or "")) return if status >= 400: _fail("POST", "/v1/terms/accept", status, body) emit(args, body) def _password_arg(args): """--password @FILE or @- (stdin), or --password-env VAR; never the password itself on the command line (the shell's history and `ps` keep it). None when neither flag was given. One trailing newline is removed.""" value, env = getattr(args, "password", None), getattr(args, "password_env", None) if value and env: die("Give the password one way: --password @FILE, --password @- or --password-env VAR.", EXIT_USAGE) if env: if env not in os.environ: die("The environment variable %s is not set." % env, EXIT_USAGE) text = os.environ[env] elif value: if not value.startswith("@"): die("Give the password as @FILE or @- (stdin), or with --password-env VAR, never inline: a value on the command " "line is kept in the shell's history.", EXIT_USAGE) if value == "@-" and sys.stdin.isatty(): # stdin is the terminal: read it without echo (review of #1108, finding 7), never as typed text on screen import getpass text = getpass.getpass("Your password (hidden): ", stream=sys.stderr) elif value == "@-": text = sys.stdin.read() else: try: with open(os.path.expanduser(value[1:])) as fh: text = fh.read() except OSError as exc: die("Cannot read %s: %s" % (value[1:], exc.strerror), EXIT_USAGE) else: return None text = text[:-1] if text.endswith("\n") else text text = text[:-1] if text.endswith("\r") else text if not text: die("The password is empty.", EXIT_USAGE) return text def cmd_account_delete(args): """DELETE /v1/me. A person re-authenticates (security review 2026-10-08, M1): the current password, and a code when two-factor is on -- given with --password @FILE|@- / --password-env VAR and --code, or asked for at a terminal when the API says it needs them. A token, and an account that never set a password (an early `lhbox signup`), need neither: the API asks for nothing more.""" body = {"confirm": args.confirm} password = _password_arg(args) if password is not None: body["current_password"] = password if args.code: body["code"] = args.code.strip() status, out = request_status(args, "DELETE", "/v1/me", body) err = (out.get("error") or {}) if isinstance(out, dict) else {} if (status == 401 and err.get("code") in ("reauth_required", "mfa_code_required") and sys.stdin.isatty() and not _want_json(args)): needs = err.get("needs") or (["code"] if err.get("code") == "mfa_code_required" else ["current_password"]) if "current_password" in needs and "current_password" not in body: import getpass body["current_password"] = getpass.getpass("Your password (hidden): ", stream=sys.stderr) if "code" in needs and "code" not in body: body["code"] = _ask("Code from your authenticator app (or a backup code): ").strip() status, out = request_status(args, "DELETE", "/v1/me", body) if status >= 400: _fail("DELETE", "/v1/me", status, out) emit(args, out) def _all_warehouses(args, projects=None): """Every catalog the caller can see, each row with its project: GET /v1/catalogs without ?project (2026-09-20 night); a control plane from before that answers 400, so the per-project loop stays as the fallback. Only a 400 falls back: any other error is the command's own (a 500 used to print its envelope, fall back, and print a second one -- two JSON documents on stderr, docs/proposals/cli-consistency.md).""" try: with _quiet(): return request(args, "GET", "/v1/catalogs")["warehouses"] except _Fatal: raise except _Refused as r: if r.status != 400: _fail("GET", "/v1/catalogs", r.status, r.parsed) except SystemExit: # a stand-in refusing (tests) pass rows = [] for proj in (projects if projects is not None else request(args, "GET", "/v1/projects")["projects"]): try: with _quiet(): out = request(args, "GET", "/v1/catalogs?" + urllib.parse.urlencode({"project": proj["project_id"]})) except _Fatal: raise except SystemExit as r: print("note: the catalogs of project %s could not be listed (HTTP %s)" % (proj.get("name"), getattr(r, "status", "error")), file=sys.stderr) continue rows.extend(dict(w, project=proj["name"], project_id=proj["project_id"]) for w in out["warehouses"]) return rows def cmd_whoami(args): """Brief by default (2026-09-20 night, item 4; the third simulated user, 2026-09-21: piped `whoami` was ~600 lines): who, the organisation, one line per catalog with the level held, the limits with their headroom, the next step -- as lines on a terminal, as a short JSON object when piped or with --json (agents prefer short JSON). `--full` is the whole answer: the tables on a terminal, GET /v1/usage plus `warehouses` as JSON.""" full = getattr(args, "full", False) # the brief view reads no per-catalog history: one day of it, not the default 7 (#3517); --full prints it whole out = request(args, "GET", "/v1/usage" if full else "/v1/usage?days=1") # what I hold on each catalog (docs/permissions-and-access.md): my_level per catalog (the API's name for # a catalog is warehouse) warehouses = [{"catalog": w["name"], "warehouse": w["name"], "warehouse_id": _cid(w), "my_level": w.get("my_level"), "via": w.get("my_via"), "project": w.get("project"), **({"status": w["status"]} if w.get("status") else {}), **({"managed": w["managed"]} if w.get("managed") else {})} for w in _all_warehouses(args, out.get("projects"))] out["warehouses"] = warehouses if full and _want_json(args): print_json(out) elif full: emit_usage_human(args, {k: v for k, v in out.items() if k != "warehouses"}, extra_tables=[("what you hold on each catalog", warehouses, ["catalog", "warehouse_id", "my_level", "via", "project"], {"warehouse_id": "catalog id"})]) else: # the organisations are a courtesy of the brief answer: a failure leaves them out, with a note, never an error # envelope before a successful answer try: with _quiet(): orgs = request(args, "GET", "/v1/orgs").get("organizations") or [] except _Fatal: raise except SystemExit as r: orgs = [] print("note: GET /v1/orgs failed (HTTP %s); organisations left out" % getattr(r, "status", "error"), file=sys.stderr) if _want_json(args): print_json(_whoami_brief_json(out, warehouses, orgs, key_source(args))) else: _whoami_brief(out, warehouses, orgs, key_source(args)) _terms_notice(args, out) def _identity_block(out): ident = {"principal_id": out.get("principal_id"), "kind": out.get("kind"), "display_name": out.get("display_name")} if out.get("email"): ident["email"] = out["email"] if out.get("acting_for") is not None or out.get("token_cannot"): # a token: whose, and what it never does (#2458) ident["acting_for"] = out.get("acting_for") ident["token_cannot"] = out.get("token_cannot") or [] return ident def _acting_for_line(out): """"Ana Lopez (admin)": the person a token acts for, with their role in each organisation.""" p = out.get("acting_for") if not p: return "nobody (the person who made this token is gone)" who = p.get("display_name") or p.get("principal_id") or "-" if p.get("email"): who += " <%s>" % p["email"] roles = sorted({r for r in (p.get("roles") or {}).values() if r}) return who + (" (%s)" % ", ".join(roles) if roles else "") def _organisations_block(out, orgs): """[{org_id, name, handle, role}] from GET /v1/orgs when it answered, else from the usage answer's organizations. The GET /v1/orgs round trip stays: /v1/usage lists only the organisations reached through a project (a token without grants sees none there), /v1/orgs every membership (high review of #683, finding 9: not safe to drop).""" role_by_org = {o.get("org_id"): o.get("role") for o in out.get("organizations") or []} if orgs: return [{"org_id": o.get("org_id"), "name": o.get("name"), "handle": o.get("handle"), "role": o.get("role") or role_by_org.get(o.get("org_id"))} for o in orgs] # the fallback when /v1/orgs failed: /v1/usage names its organisations since 2026-09-28 (#683) return [{"org_id": o.get("org_id"), "name": o.get("name"), "handle": o.get("handle"), "role": o.get("role")} for o in out.get("organizations") or []] def _brief_limits(out): """Every limit as one object: {limit, enforced} for all of them (enforced from limits_detail; the guidelines say false), plus current / headroom where the answer carries them -- the two storage tiers from the scope's block and the catalog count per project (docs/audit-and-quota.md: only the enforced ones can be met by failing).""" detail = out.get("limits_detail") or {} limits = out.get("limits") or {} projects = out.get("projects") or [] res = {} for name, value in limits.items(): res[name] = {"limit": value, "enforced": (detail.get(name) or {}).get("enforced")} for tier_key in ("storage_bytes", "public_storage_bytes"): blocks = [] # one scope per organisation: every project of it carries the same block for p in projects: if p.get(tier_key) and p[tier_key].get("scope_id") not in [x.get("scope_id") for x in blocks]: blocks.append(p[tier_key]) if blocks: res.setdefault(tier_key, {"limit": blocks[0].get("limit"), "enforced": None}) def figures(b): return {**({"limit": b["limit"]} if b.get("limit") is not None else {}), "current": b.get("current"), "headroom": b.get("headroom"), "unmetered": b.get("unmetered", b.get("current") is None), "over_limit": b.get("over_limit", False), "scope": b.get("scope"), "scope_id": b.get("scope_id")} # each scope's figures whole, its own limit included: the flat limit of a person in two organisations is the # free plan's, not either scope's (#2209); several scopes go per_scope, as warehouses go per_project if len(blocks) == 1: res[tier_key].update(figures(blocks[0])) else: res[tier_key]["per_scope"] = [{"limit": b.get("limit"), **figures(b)} for b in blocks] per = [{"project": p.get("name"), "project_id": p.get("project_id"), **{k: p["warehouses"].get(k) for k in ("current", "limit", "headroom")}} for p in projects if p.get("warehouses")] if per: res.setdefault("warehouses", {"limit": per[0]["limit"], "enforced": None}) res["warehouses"]["per_project"] = per if len(per) == 1: res["warehouses"].update({"current": per[0]["current"], "headroom": per[0]["headroom"], "project": per[0]["project"]}) return res def _next_hint(warehouses): warehouses = _own_catalogs(warehouses) # the system catalog is never "the only catalog" beside yours if not warehouses: return "lhbox catalog create (a catalog first)" if any(w.get("status") == "provisioning" for w in warehouses): names = ", ".join(w["catalog"] for w in warehouses if w.get("status") == "provisioning") return "wait 30 s: %s is still provisioning (its storage has not accepted a write yet); then lhbox doctor" % names if len(warehouses) == 1: return "lhbox doctor, then lhbox connect --engine duckdb (the only catalog is the default)" return "lhbox connect --catalog --engine duckdb (%d catalogs: name one); lhbox doctor --catalog " % len(warehouses) def _whoami_brief_json(out, warehouses, orgs, key_src="credentials file"): """The brief object: identity, organisations, catalogs with the level held, limits with headroom and enforced, the next step. `lhbox whoami --full` is GET /v1/usage plus warehouses[].""" return {"identity": _identity_block(out), "organisations": _organisations_block(out, orgs), "catalogs": [{k: v for k, v in w.items() if k != "warehouse"} for w in warehouses], "limits": _brief_limits(out), "next": _next_hint(warehouses), "full": "lhbox whoami --full", "key": {"source": key_src, "switch": KEY_SWITCH_HINT}} def _whoami_brief(out, warehouses, orgs, key_src="credentials file"): """The eight lines a person or an agent needs first; everything else is `--full`.""" def row(label, value): print("%-14s %s" % (label, value)) kind = out.get("kind") or "-" name = out.get("display_name") or "-" who = ("person %s" % name if kind == "human" else "token %r" % name if kind == "token" else "%s %r (a token)" % (kind, name)) if out.get("email"): who += " <%s>" % out["email"] row("identity", who) if kind == "token" and ("acting_for" in out or out.get("token_cannot")): row("acting for", _acting_for_line(out)) for i, c in enumerate(out.get("token_cannot") or []): row("tokens cannot" if i == 0 else "", c) role_by_org = {o.get("org_id"): o.get("role") for o in out.get("organizations") or []} if orgs: for o in orgs: handle = " (%s)" % o["handle"] if o.get("handle") else "" row("organisation", "%s%s, %s" % (o.get("name") or o.get("org_id"), handle, o.get("role") or role_by_org.get(o.get("org_id")) or "-")) elif role_by_org: for oid, role in role_by_org.items(): row("organisation", "%s, %s" % (oid, role or "-")) else: row("organisation", "none yet") if warehouses: for i, w in enumerate(warehouses): via = " via %s" % w["via"] if w.get("via") else "" row("catalogs" if i == 0 else "", "%-20s %-22s id %s" % (w["catalog"], (w.get("my_level") or "none") + via, _cid(w))) else: row("catalogs", "none visible") projects = out.get("projects") or [] tiers = [] for p in projects: for tier, key in (("private", "storage_bytes"), ("public", "public_storage_bytes")): s = p.get(key) or {} if s and (s.get("scope_id"), tier) not in {(t[0], t[1]) for t in tiers}: tiers.append((s.get("scope_id"), tier, s)) if tiers: row("storage", "; ".join("%s (%s, headroom %s)" % (_of(s.get("current"), s.get("limit"), True), tier, fmt_bytes(s.get("headroom"))) for _, tier, s in tiers)) for i, p in enumerate(projects): c = p.get("warehouses") or {} row("catalog limit" if i == 0 else "", "%s in project %s (headroom %s)" % (_of(c.get("current"), c.get("limit")), p.get("name"), c.get("headroom", "-"))) row("next", _next_hint(warehouses)) row("key", "from %s; %s" % (key_src, KEY_SWITCH_HINT)) print("(lhbox whoami --full: every limit, project and organisation as tables; --json: this view as an object, --json --full the API's answer)") def _terms_notice(args, out): """Terms are a person's (review 2026-09-20 night, item 6): a token is never asked to accept them. Accounts that predate a Terms version (or were created by an operator) have not accepted the version in force; say so ONCE per credentials file (item 5, the same night: every command used to repeat it), on stderr, so scripts reading stdout are unaffected. The file entry remembers `terms_notice_shown_for: `; a new version is a new notice. A key that came from the environment or --api-key has no entry, so it is told each time.""" if out.get("kind") != "human": return try: with _quiet(): t = request(args, "GET", "/v1/terms") except _Fatal: raise except SystemExit: return if t.get("accepted_current"): return version = t.get("current_version") entry = _saved_connection(args) or {} if entry.get("api_key") and entry.get("terms_notice_shown_for") == version: return sys.stderr.write("note: this account has not accepted Terms %s (%s). Read them, then run: lhbox terms --accept\n" % (version, t.get("terms_url"))) if entry.get("api_key"): try: with _cred_lock(): # the entry read again under the lock: another login may have replaced it (#2642) now = _saved_connection(args) or {} if now.get("api_key") == entry["api_key"]: save_credentials(args, dict(now, terms_notice_shown_for=version)) except OSError: pass # only the reminder's memory: the command already answered (#2086) def cmd_project_create(args): body = {"name": args.name} if args.provider: body["provider"] = args.provider if args.region: body["region"] = args.region emit(args, request(args, "POST", "/v1/projects", body, args.idempotency_key)) def cmd_project_list(args): out = request(args, "GET", "/v1/projects") emit(args, out["projects"], ["name", "project_id", "provider", "region"]) def cmd_warehouse_create(args): """`lhbox catalog create ` places the catalog in the organisation's default project (created when there is none); --project names another. The call is slow (identities and policies at the store, ~90 s on a busy host): the long timeout, a progress line every ~10 s for a person, and -- should the server answer 202 with status: provisioning -- GET /v1/catalogs/{id} polled until the status is ready (inert on today's 201).""" name = getattr(args, "name_arg", None) or getattr(args, "name", None) if getattr(args, "name_arg", None) and getattr(args, "name", None) and args.name_arg != args.name: die("Two names given: %r and --name %r. Name one." % (args.name_arg, args.name), EXIT_USAGE) if not name: die("Name the catalog: lhbox catalog create (lowercase letters, digits, _; a letter first)", EXIT_USAGE) body = {"name": name} if args.project: body["project_id"] = args.project if getattr(args, "default_format_version", None) is not None: body["default_format_version"] = args.default_format_version if getattr(args, "access", None): body["org_access"] = GENERAL_ACCESS[args.access] status, out = request_slow(args, "POST", "/v1/catalogs", body, args.idempotency_key, what="creating the catalog") if status == 202 and out.get("status") == "provisioning" and _cid(out) and not getattr(args, "no_wait", False): out = _poll_until_ready(args, out) # #2338: a new catalog has no AGENTS.md; agents follow what a command answers, so the answer names what finishes it hint = None if isinstance(out, dict) and out.get("name"): hint = ("once its tables are in: lhbox catalog agents-md %s --set AGENTS.md (what the tables mean, how they " "join, units, caveats, freshness)" % out["name"]) if hint and _want_json(args): out = {**out, "next_step": {"agents_md": hint}} emit(args, out) if hint and not _want_json(args): print("next: " + hint) def _poll_until_ready(args, out, max_seconds=600): """GET /v1/catalogs/{id} every PROVISION_POLL_INTERVAL s until `status` is ready (or anything but provisioning); a person sees a line every ~10 s. Gives up after max_seconds with the last row and a warning, never an error: the catalog exists.""" talk = not _want_json(args) t0 = time.time() next_note = t0 + PROGRESS_INTERVAL while out.get("status") == "provisioning" and time.time() - t0 < max_seconds: time.sleep(PROVISION_POLL_INTERVAL) st, row = request_status(args, "GET", "/v1/catalogs/" + urllib.parse.quote(_cid(out), safe="")) if st == 200: out = {**out, **row} if talk and time.time() >= next_note: print("provisioning the catalog's storage… %d s" % int(time.time() - t0), file=sys.stderr, flush=True) next_note = time.time() + PROGRESS_INTERVAL if out.get("status") == "provisioning": print("warning: still provisioning after %d s; `lhbox catalog get %s` shows when it is ready." % (max_seconds, out.get("name")), file=sys.stderr) return out def named_catalog(args, verb): """The catalog a destructive or account-changing verb names (positional, or the hidden --catalog / --warehouse twins): required, never the only-catalog default -- a rotate or a delete must not fall on a guess.""" ref = catalog_arg(args) if not ref: die("Name the catalog: lhbox catalog %s (its id works too; lhbox catalog list shows both)" % verb, EXIT_USAGE) return ref def confirmed_catalog(args, verb, need_name, deleted_ok=False): """(catalog ref, the confirmation the API wants) for the verbs that take --confirm / --yes. `--confirm NAME` alone names the catalog as well (2026-09-21: `publish --confirm sales` without --catalog was refused). need_name: the API wants the name typed out (delete, publish); a bare --yes then confirms the positional NAME, and is refused when only an id was given. Otherwise (unpublish, rotate, …) the flag is accepted and nothing more.""" confirm = getattr(args, "confirm", None) named = catalog_arg(args) ref = named or (confirm if isinstance(confirm, str) else None) if not ref: die("Name the catalog: lhbox catalog %s %s" % (verb, " --confirm" if need_name else ""), EXIT_USAGE) if isinstance(confirm, str) and named and confirm != named and not UUID_RE.match(named): die("--confirm %r does not match the catalog named, %r. Type the same name, or a bare --confirm." % (confirm, named), EXIT_USAGE) if not need_name: return ref, None if confirm is None: die("lhbox catalog %s %s wants a confirmation as well: --confirm (or --yes; --confirm spells it out)." % (verb, ref), EXIT_USAGE) if confirm is True: # the API wants the name typed out; the name was typed as the positional -- or the id was, and the name is looked up confirm = ref if not UUID_RE.match(ref) else _catalog_name_of(args, ref, deleted_ok) return ref, confirm def _catalog_name_of(args, cid, deleted_ok): """The name of catalog `cid`, for a --yes that must type it. deleted_ok (`delete --purge`, issue #1980): a catalog in its grace period answers 404 warehouse_deleted with state retained and its name, which is the name to type.""" path = "/v1/catalogs/" + urllib.parse.quote(cid, safe="") if not deleted_ok: return request(args, "GET", path).get("name") try: with _quiet(): return request(args, "GET", path).get("name") except _Fatal: raise except _Refused as r: err = (r.parsed or {}).get("error") if isinstance(r.parsed, dict) else None if r.status == 404 and isinstance(err, dict) and err.get("code") == "warehouse_deleted" \ and err.get("state") == "retained" and isinstance(err.get("name"), str): return err["name"] _fail("GET", path, r.status, r.parsed) # a catalog's general access for its organisation's members, as the CLI spells it -> the API's `org_access` GENERAL_ACCESS = {"restricted": "none", "organisation": "read"} GENERAL_ACCESS_WORDS = {"none": "Restricted (only the people and tokens given access)", "read": "Everyone in the organisation (every member reads it)"} def _general_access_human(out): return GENERAL_ACCESS_WORDS.get(out.get("org_access") or "none", out.get("org_access")) def _set_general_access(args, target): """`lhbox catalog update --access restricted|organisation`: PUT /v1/catalogs/{id}/org-access. Opening gives every member of the organisation read on the catalog; making it Restricted takes the catalog from the members who read it only as members and replaces the key pairs they fetched, so it is confirmed first: a person at a terminal is told how many members that is and asked, anyone else passes --yes (a new flag: no script to keep working).""" value = GENERAL_ACCESS[args.access] path = "/v1/catalogs/%s/org-access" % urllib.parse.quote(target, safe="") if value == "none" and not getattr(args, "yes", False): now = request(args, "GET", path) if now.get("org_access") == "read": m = now.get("members") or {} what = ("Make catalog %s Restricted: %s member(s) who read it only as members of the organisation lose it%s" % (now.get("name") or target, m.get("by_membership", "?"), ", and the key pairs they fetched are replaced" if m.get("key_holders") else "")) if sys.stdin.isatty() and sys.stdout.isatty() and not _want_json(args): if _ask("%s? [y/N] " % what).strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was changed.", EXIT_USAGE) else: die_json("confirmation_required", what + ".", EXIT_USAGE, org_access="read", members=m, remedy="Pass --yes to do it: lhbox catalog update %s --access restricted --yes" % target) out = request(args, "PUT", path, {"org_access": value}) if _want_json(args): emit(args, out) return print("%s: general access %s: %s" % (out.get("name"), "changed" if out.get("changed") else "unchanged", _general_access_human(out))) if out.get("note"): print(out["note"]) rotated = out.get("keys_rotated") or [] if rotated: print("keys replaced: %s (fetch a fresh recipe: lhbox connect)" % ", ".join(k.get("credential") or "-" for k in rotated)) if out.get("tokens_capped") or out.get("agents_capped"): print("lowered with them: %d token(s), %d hosted agent(s) those members made" % (len(out.get("tokens_capped") or []), len(out.get("agents_capped") or []))) def cmd_warehouse_update(args): """Change a catalog's settings: today the Iceberg format version LakehouseBox's own create paths give its new tables (`table create` without --format-version, and table import). An engine's own CREATE TABLE keeps the version the engine chose; existing tables are unchanged. The catalog is named, positional or --catalog: a settings change never falls back to "your only catalog".""" target = catalog_arg(args) if not target: die("Name the catalog to change: lhbox catalog update --default-format-version 2|3 (or --catalog).", EXIT_USAGE) if getattr(args, "access", None): # general access is its own route with its own consequences (keys replaced, a confirmation): changed alone if any(getattr(args, k, None) is not None for k in ("default_format_version", "snapshot_retention_days", "virtual_host", "edge_reads")): die("--access is changed on its own: run it apart from the other settings.", EXIT_USAGE) return _set_general_access(args, target) body = {} if getattr(args, "default_format_version", None) is not None: body["default_format_version"] = args.default_format_version keep = getattr(args, "snapshot_retention_days", None) if keep is not None: if keep == "default": body["snapshot_retention_days"] = None elif keep.isdigit(): body["snapshot_retention_days"] = int(keep) else: die("--snapshot-retention-days takes a whole number of days (1-90) or `default`.", EXIT_USAGE) if getattr(args, "virtual_host", None): body["virtual_host"] = args.virtual_host == "on" if getattr(args, "edge_reads", None): body["edge_reads"] = args.edge_reads == "on" if not body: die("Say what to change: --access restricted|organisation, --default-format-version 2|3, " "--snapshot-retention-days N|default and/or --virtual-host on|off.", EXIT_USAGE) out = request(args, "PATCH", "/v1/catalogs/" + urllib.parse.quote(target, safe=""), body) if not _want_json(args): changed = out.get("updated") or [] previous = out.get("previous") or {} if "default_format_version" in body: prev = previous.get("default_format_version") if "default_format_version" in changed: print("%s: new tables LakehouseBox creates are now format version %s (was %s)." % (out.get("name"), out.get("default_format_version"), prev)) else: print("%s: new tables LakehouseBox creates are already format version %s; nothing changed." % (out.get("name"), out.get("default_format_version"))) if "snapshot_retention_days" in body: sr = out.get("snapshot_retention") or {} state = "changed" if "snapshot_retention_days" in changed else "unchanged" print("%s: snapshot retention %s: %s" % (out.get("name"), state, sr.get("note") or out.get("snapshot_retention_days"))) if "virtual_host" in body: state = "changed" if "virtual_host" in changed else "unchanged" if out.get("virtual_host"): print("%s: virtual-hosted access on (%s): https://%s.s3. is served; its TLS certificate lists the " "bucket name in the public Certificate Transparency logs." % (out.get("name"), state, out.get("bucket"))) else: print("%s: virtual-hosted access off (%s): no new or renewed certificate; one already issued keeps working " "until it is due for renewal (within about 60 days)." % (out.get("name"), state)) if "edge_reads" in body: state = "changed" if "edge_reads" in changed else "unchanged" if out.get("edge_reads"): print("%s: edge caching on (%s): its read sessions come through the CDN by themselves; the edge " "caches its files and holds its read-only key inside each hour-long edge credential." % (out.get("name"), state)) if out.get("edge_reads_note"): print(out["edge_reads_note"]) else: print("%s: edge caching off (%s): read sessions use the storage again; edge credentials already handed out stop within the hour." % (out.get("name"), state)) fmt = out.get("format") or {} if fmt and "default_format_version" in body: print("written by %s; read but not written by %s" % (", ".join(fmt.get("writers") or []) or "-", ", ".join(fmt.get("readers") or []) or "-")) return emit(args, out) SCHEMA_EXAMPLE = ('{"type":"struct","schema-id":0,"identifier-field-ids":[1],' '"fields":[{"id":1,"name":"id","required":true,"type":"long"}]}') def read_schema_file(path): try: with open(path) as fh: return json.load(fh) except OSError as e: die_json("schema_file_unreadable", "Cannot read --schema-file %s: %s" % (path, e.strerror), path=path, remedy="Point --schema-file at a readable file, or use the repeatable " "--column name:type[:required][:identifier] shorthand instead.") except ValueError as e: die_json("schema_file_not_json", "--schema-file %s is not valid JSON: %s" % (path, e), path=path, expected_shape=SCHEMA_EXAMPLE, remedy="Pass a full Iceberg schema object shaped like 'expected_shape', or use the " "repeatable --column name:type[:required][:identifier] shorthand instead.") def cmd_table_create(args): # the table and its catalog first: naming them is the command line's job (exit 6), as when argparse required them ns, name = _table_ref(args) catalog = _table_catalog(args, "table create") if args.schema_file: schema = read_schema_file(args.schema_file) elif args.column: schema = parse_columns(args.column) else: die("Give either --schema-file or one or more --column name:type[:required][:identifier].") body = {"catalog_id": catalog, "namespace": ns, "name": name, "schema": schema} # without --format-version nothing is sent: the API applies the catalog's default_format_version if args.format_version is not None: body["format_version"] = args.format_version if getattr(args, "partition", None): body["partition"] = list(args.partition) # the API checks each against the schema (400 names the entry) out = request(args, "POST", "/v1/tables", body, args.idempotency_key) # Say which version the table actually has and where it came from (the flag, or the catalog's default). if out.get("format_version") is not None: source = out.get("format_version_source") print("format-version %s (%s)" % (out["format_version"], "requested" if source == "request" else "the catalog's default; --format-version overrides it" if source == "catalog_default" else "reported by the catalog"), file=sys.stderr) # Tell the caller plainly if the engine silently gave them something else. if not out.get("format_version_honoured", True): print("warning: asked for format-version %s, got %s" % (out.get("format_version_requested"), out.get("format_version")), file=sys.stderr) # The table exists now, so this cannot be an error -- but it has to be seen *here*, before the # caller writes a loader against a table its engine cannot INSERT into. for w in out.get("warnings", []): print("warning: " + w, file=sys.stderr) if out.get("partition"): print("partitioned by %s" % ", ".join(out["partition"]), file=sys.stderr) emit(args, out) def cmd_warehouse_rotate(args): ref = named_catalog(args, "rotate") _confirm_irreversible(args, "Rotate the credentials of catalog %s (the old keys are refused at once)" % ref) _, out = request_slow(args, "POST", "/v1/catalogs/%s/rotate" % urllib.parse.quote(ref), what="rotating the catalog's credentials") if not getattr(args, "show_secrets", False): out = masked_recipe(out) # both new secrets; `lhbox connect --show-secrets` prints them when an engine needs one emit(args, out) def _grant_scope_text(row): """What a holder holds below the catalog, as a person reads it (#2021): "ns distrito_a: write; table geo.t: read". A grant that does not apply (its holder's catalog or namespace grant covers it) is marked so; "-" when there is none.""" parts = [] for key, apply_key, label in (("namespaces", "namespaces_apply", "ns"), ("tables", "tables_apply", "table")): for g in row.get(key) or []: name = ("%s.%s" % (g.get("namespace"), g.get("table"))) if g.get("table") else g.get("namespace") text = "%s %s: %s" % (label, name, g.get("level")) if g.get("via") == "group_rule": text += " (group rule)" if row.get(apply_key) is False: text += " (not in effect)" parts.append(text) return "; ".join(parts) or "-" def cmd_warehouse_grants(args): rows = request(args, "GET", "/v1/catalogs/%s/grants" % urllib.parse.quote(resolve_catalog(args))) if _want_json(args) or not isinstance(rows, list): emit(args, rows) return # a namespace or table holder is `none`/`none` on the catalog itself: what it holds below it is the `below` column emit(args, [dict(r, below=_grant_scope_text(r)) for r in rows], ["display", "kind", "level", "via", "below", "principal_id"]) def _grant_scope(args, ref): """(namespace, table) a grant or revocation names: --namespace NS alone, or --table NS.TABLE (the table spelling of convention 1; a leading catalog part must be this catalog's). (None, None) for the catalog itself.""" ns, tref = getattr(args, "namespace", None), getattr(args, "table", None) if not tref: return ns, None parts = tref.split(".") if len(parts) == 3 and parts[0] in (ref, getattr(args, "catalog", None)): parts = parts[1:] if len(parts) != 2 or not all(parts): die("--table is NS.TABLE: the namespace and the table of this catalog, e.g. --table distrito_centro.licencias.", EXIT_USAGE) if ns and ns != parts[0]: die("--namespace %r and --table %r name different namespaces. Name one." % (ns, tref), EXIT_USAGE) return parts[0], parts[1] def cmd_warehouse_grant(args): ref = named_catalog(args, "grant") ns, table = _grant_scope(args, ref) body = {"level": args.level} if ns: body["namespace"] = ns # one namespace of the catalog (an enterprise feature, admins only) if table: body["table"] = table # ... or one table of it (table-level grants, the same rules) if getattr(args, "all_catalogs", False): if not ns: die("--all-catalogs goes with --namespace on the system catalog (lhbox): it says that the schema is about " "every catalog of the organisation. It does not grant several catalogs; a grant is on one.", EXIT_USAGE) body["confirm"] = "all_catalogs" # a schema of the system catalog is about every catalog: said so emit(args, request(args, "PUT", "/v1/catalogs/%s/grants/%s" % (urllib.parse.quote(ref), urllib.parse.quote(args.principal)), body)) def cmd_warehouse_revoke(args): ref = named_catalog(args, "revoke") ns, table = _grant_scope(args, ref) what = ("table %s.%s of catalog %s" % (ns, table, ref) if table else "namespace %s of catalog %s" % (ns, ref) if ns else "catalog " + ref) _confirm_irreversible(args, "Revoke %s's grant on %s" % (args.principal, what)) path = "/v1/catalogs/%s/grants/%s" % (urllib.parse.quote(ref), urllib.parse.quote(args.principal)) if ns: path += "?" + urllib.parse.urlencode({"namespace": ns, **({"table": table} if table else {})}) emit(args, request(args, "DELETE", path)) def cmd_warehouse_delete(args): """Delete a catalog. The service keeps it restorable for a grace period (status `retained`, purge_after, `lhbox catalog restore`); --purge deletes it at once, for good -- also a catalog already in its grace period (then pass the name: --confirm , or the id with --yes: the name is read from its tombstone).""" ref, confirm = confirmed_catalog(args, "delete", need_name=True, deleted_ok=bool(getattr(args, "purge", False))) body = {"confirm": confirm} if getattr(args, "purge", False): body["purge"] = True _, out = request_slow(args, "DELETE", "/v1/catalogs/%s" % urllib.parse.quote(ref), body, what="deleting the catalog") if out.get("warning"): print("warning: " + out["warning"], file=sys.stderr) if out.get("status") == "retained" and not _want_json(args): print("deleted %s; restorable until %s with: lhbox catalog restore %s" % (out.get("name"), out.get("purge_after"), _cid(out)), file=sys.stderr) emit(args, out) def cmd_warehouse_restore(args): """Restore a catalog in its deletion grace period, by id or name (admin). Same id, name, buckets and tables; a new key pair if its credentials were already revoked (fetch a fresh recipe with `lhbox connect`).""" ref = catalog_arg(args) if not ref: die("Name the catalog to restore: lhbox catalog restore ", EXIT_USAGE) out = request(args, "POST", "/v1/catalogs/%s/restore" % urllib.parse.quote(ref, safe=""), {}) emit(args, out) # ---------------------------------------------------------------- uploaders: write-only credentials for the blob bucket # platform/docs/blob-uploader.md. The secret comes back from the API exactly once. The same discipline as the # account's keys: it goes to a 0600 file (--save) or to the terminal on request (--show-key), and without either # flag the command stops BEFORE calling the API, so no identity is created whose secret nobody received. def _uploader_masked(out, secret): """The same answer with the secret replaced wherever it appears (the field and every recipe): mask_secrets, the one rule.""" return mask_secrets(out, [secret]) def save_uploader_file(path, out): """The pair and what a device needs to use it, one JSON file, mode 0600 whether created or overwritten (the mode on os.open applies only to a new file; fchmod after open is what guarantees it, as save_credentials).""" path = os.path.expanduser(path) entry = {k: out.get(k) for k in ("uploader_id", "name", "warehouse_id", "bucket", "prefix", "list", "endpoint", "region", "access_key_id", "secret_access_key", "expires_at")} if out.get("dropbox"): # research/32 §4: the drop-box login, shown once like the secret entry["dropbox"] = out["dropbox"] _write_json_0600(path, entry) # whole or not at all, as the sink files (#2947) return path def _save_target_problem(path): """Why `path` cannot be written as a --save file, or None; checked BEFORE the API creates anything (#1932). The file is no folder and, when it exists, writable; else the nearest existing ancestor is a writable folder. A check, not a guarantee (a full disk; root passes every access test): the write after the create has its own undo.""" path = os.path.abspath(os.path.expanduser(path)) if os.path.isdir(path): return "it is a folder" if os.path.lexists(path): return None if os.access(path, os.W_OK) else "the file is not writable" folder = os.path.dirname(path) while not os.path.lexists(folder) and os.path.dirname(folder) != folder: folder = os.path.dirname(folder) if not os.path.isdir(folder): return "%s is not a folder" % folder if not os.access(folder, os.W_OK | os.X_OK): return "the folder %s is not writable" % folder return None def _uploader_save_failed(args, ref, out, exc): """The uploader exists but its file could not be written (#1932): revoke it -- its secret is never shown instead, it would land in a transcript -- and say what was undone; when the revoke fails too, name the command that does it.""" reason = "%s: %s" % (type(exc).__name__, getattr(exc, "strerror", None) or exc) who = out.get("uploader_id") or out.get("name") st = 0 if who: _SILENT.on = True # an unreachable API raises SystemExit here without printing try: st, _ = request_status(args, "DELETE", "/v1/catalogs/%s/uploaders/%s" % (urllib.parse.quote(ref), urllib.parse.quote(str(who))), timeout=180) except (SystemExit, Exception): # noqa: BLE001 - reported below as not revoked st = 0 finally: _SILENT.on = False revoked = 200 <= st < 300 detail = {"save": args.save, "uploader": out.get("name"), "uploader_revoked": revoked} if revoked: die_json("uploader_not_saved", "Uploader %s was created but its secret could not be saved to %s (%s); the uploader was " "revoked, so nothing is left behind." % (out.get("name"), args.save, reason), EXIT_ERROR, remedy="Fix the --save path and run the same command again.", **detail) die_json("uploader_not_saved", "Uploader %s was created but its secret could not be saved to %s (%s), and it could not be " "revoked; its secret was not shown and cannot be shown again." % (out.get("name"), args.save, reason), EXIT_ERROR, remedy="Revoke it: lhbox catalog uploader revoke %s --uploader %s --yes; then fix the --save path and run the " "same command again." % (ref, out.get("name")), **detail) def cmd_uploader_create(args): if not args.save and not args.show_key: die("The uploader's secret is shown once and belongs in no transcript: pass --save (written 0600, " "nothing printed) or --show-key (printed once). Nothing was created.", EXIT_USAGE) held = os.path.expanduser(args.save) if args.save else None if held and os.path.isfile(held) and os.path.getsize(held) > 0: # a new uploader's secret goes to a new file (#2947): an existing one may hold another uploader's secret, which # the API cannot show again -- `sink create --save` refuses the same (#2501) die_json("save_file_exists", "--save %s already exists and is not empty. Nothing was created." % args.save, EXIT_USAGE, save=args.save, remedy="A new uploader's secret goes to a new file: choose another path, or remove this " "one if it belongs to an uploader you revoked.") problem = _save_target_problem(args.save) if args.save else None if problem: die_json("save_path_unwritable", "Cannot write --save %s: %s. Nothing was created." % (args.save, problem), EXIT_USAGE, save=args.save, remedy="Point --save at a file in a folder you can write.") body = {"name": args.name, "prefix": args.prefix or "", "list": bool(args.list)} if args.expires_at: body["expires_at"] = args.expires_at # the store's IAM writes (the server lists them in iam_writes; two since the data path moved to bucket policies), up to 10 s each at the host's current identity count if getattr(args, "protocols", None): body["protocols"] = [p.strip() for p in args.protocols.split(",") if p.strip()] ref = resolve_catalog(args) out = request(args, "POST", "/v1/catalogs/%s/uploaders" % urllib.parse.quote(ref), body, timeout=180) secret = out["secret_access_key"] box = out.get("dropbox") or None shown = dict(out) if args.save: shown = dict(out) if args.show_key else _uploader_masked(out, secret) if box and not args.show_key: shown = mask_secrets(shown, [box["password"]]) try: shown["saved_to"] = save_uploader_file(args.save, out) except OSError as exc: _uploader_save_failed(args, ref, out, exc) if _want_json(args): print_json(shown) return print("Uploader %s created for catalog %s (identity %s)." % (out["name"], out.get("warehouse_name") or _cid(out), out["iam_user"])) print(" scope: %s" % out.get("scope")) print(" endpoint: %s bucket: %s region: %s" % (out["endpoint"], out["bucket"], out["region"])) print(" access_key_id: %s" % out["access_key_id"]) if args.show_key: print(" secret: %s <- shown once%s" % (secret, ("; saved to " + shown["saved_to"]) if args.save else "")) else: print(" secret: saved to %s (not shown; the API cannot show it again)" % shown["saved_to"]) if out.get("expires_at"): print(" expires_at: %s" % out["expires_at"]) print(" cost: %s (%d IAM writes at the store; nothing is re-written later)" % (" + ".join(out.get("iam_writes") or []), len(out.get("iam_writes") or []))) if box: print(" drop box: %s on %s (FTP port %s, passive %s; SFTP port %s)%s" % ( "/".join(box["protocols"]), box.get("host") or "(not deployed yet)", box["ftp_port"], box["passive_ports"], box["sftp_port"], "" if box.get("host") else " -- " + box.get("note", ""))) print(" login: %s" % box["username"]) if args.show_key: print(" password: %s <- shown once" % box["password"]) else: print(" password: saved to %s (not shown)" % shown["saved_to"]) if box.get("ftp"): print(" note: %s" % box["ftp"]) print("Revoke with: lhbox catalog uploader revoke %s --uploader %s" % (out.get("warehouse_name") or _cid(out), out["name"])) if args.show_key and out.get("recipe", {}).get("aws_cli"): print("Recipe (aws cli):") print(out["recipe"]["aws_cli"]) def cmd_uploader_list(args): q = "?include_revoked=true" if args.all else "" rows = request(args, "GET", "/v1/catalogs/%s/uploaders%s" % (urllib.parse.quote(resolve_catalog(args)), q))["uploaders"] if _want_json(args): print_json(rows) return for r in rows: r["list"] = "yes" if r.get("list") else "no" emit(args, rows, ["name", "uploader_id", "prefix", "list", "access_key_id", "status", "expires_at", "created_at"], {"uploader_id": "uploader id", "access_key_id": "access key id", "expires_at": "expires", "created_at": "created"}) def cmd_uploader_revoke(args): ref = resolve_catalog(args) _confirm_irreversible(args, "Revoke uploader %s of catalog %s (its key is deleted at the store)" % (args.uploader, ref)) out = request(args, "DELETE", "/v1/catalogs/%s/uploaders/%s" % (urllib.parse.quote(ref), urllib.parse.quote(args.uploader)), timeout=180) if out.get("warning"): print("warning: " + out["warning"], file=sys.stderr) emit(args, out) # ---------------------------------------------------------------- lifecycle: expiry rules on the catalog's blob bucket # platform/docs/lifecycle.md. `set` MERGES one rule into the configuration by id (the S3 API replaces the whole # document, so the CLI reads first): two `set` calls for two prefixes leave two rules. --replace-all drops the rest. def _lifecycle_rule_view(r): """One rule as a person reads it in the table.""" exp = ("%d days" % r["expire_days"]) if r.get("expire_days") is not None else (r.get("expire_date") or "-") extras = [] if r.get("tags"): extras.append("tags " + ",".join("%s=%s" % kv for kv in sorted(r["tags"].items()))) if r.get("size_greater_than") is not None: extras.append("size > %d" % r["size_greater_than"]) if r.get("size_less_than") is not None: extras.append("size < %d" % r["size_less_than"]) if r.get("other"): extras.append("+" + ",".join(r["other"])) return {"id": r.get("id"), "prefix": r.get("prefix") if r.get("prefix") else "(whole bucket)", "expires": exp, "abort_multipart": ("%d days" % r["abort_incomplete_multipart_days"]) if r.get("abort_incomplete_multipart_days") is not None else "-", "status": "enabled" if r.get("enabled") else "disabled", "filters": "; ".join(extras) or "-"} def _emit_lifecycle(args, out, verb): if _want_json(args): print_json(out) return rules = out.get("rules") or [] print("%s: %d lifecycle rule%s on %s (catalog %s)." % (verb, len(rules), "" if len(rules) == 1 else "s", out.get("bucket"), out.get("name") or _cid(out))) if rules: _table([_lifecycle_rule_view(r) for r in rules], ["id", "prefix", "expires", "abort_multipart", "status", "filters"], {"abort_multipart": "abort multipart after"}) if rules and out.get("note"): print("# " + out["note"]) def _lifecycle_rule_id_for(args): if args.id: return args.id prefix = args.prefix or "" slug = re.sub(r"[^A-Za-z0-9._-]+", "-", prefix.strip("/")).strip("-") or "bucket" if len(slug) > 200: # the control plane's _lifecycle_slug: an id stays within 255 characters (#2613) slug = slug[:187].rstrip("-") + "-" + hashlib.sha256(prefix.encode()).hexdigest()[:12] return slug def _lifecycle_merge_id(current, prefix, derived): """The id a `set` without --id gives its rule (issue #2020): the id of the rule with the SAME prefix, which it replaces; else the derived slug, suffixed (-2, -3, ...) while another prefix's rule holds it. Distinct prefixes share a slug (`camera/` and `camera`, `""` and `/`): matching by the slug silently dropped the first rule.""" # a rule set outside this command (tag or size filters) is not "the same rule" for its prefix: replacing it would lose # its filters, so it stays in the way below (the refusal names --replace-all), as before same = [r for r in current if (r.get("prefix") or "") == prefix and r.get("id") and r.get("expressible", True)] if len(same) > 1: die("The catalog has %d lifecycle rules with the prefix %r (%s); name the one to replace with --id." % (len(same), prefix, ", ".join(r["id"] for r in same)), EXIT_USAGE) if same: return same[0]["id"] taken = {r.get("id") for r in current} rid, n = derived, 2 while rid in taken: rid, n = "%s-%d" % (derived, n), n + 1 return rid def cmd_lifecycle_set(args): if args.expire_days is None and not args.expire_date and args.abort_multipart_days is None: die("A rule needs --expire-days N, --expire-date YYYY-MM-DD or --abort-multipart-days N (or several).", EXIT_USAGE) if args.expire_days is not None and args.expire_date: die("A rule expires by --expire-days OR by --expire-date, not both.", EXIT_USAGE) if args.expire_days is not None and args.expire_days < 1: die("--expire-days must be at least 1: the store accepts 0 and never fires such a rule. For \"delete now\" " "use --expire-date with a date in the past.", EXIT_USAGE) rule = {"id": _lifecycle_rule_id_for(args), "prefix": args.prefix or "", "enabled": not args.disabled} if args.expire_days is not None: rule["expire_days"] = args.expire_days if args.expire_date: rule["expire_date"] = args.expire_date if args.abort_multipart_days is not None: rule["abort_incomplete_multipart_days"] = args.abort_multipart_days cat = urllib.parse.quote(resolve_catalog(args)) kept = [] if not args.replace_all: current = request(args, "GET", "/v1/catalogs/%s/lifecycle" % cat).get("rules") or [] if not args.id: rule["id"] = _lifecycle_merge_id(current, rule["prefix"], rule["id"]) blocked = [r for r in current if r.get("id") != rule["id"] and not r.get("expressible", True)] if blocked: die("The bucket carries %d rule(s) set outside this command (tag or size filters, an id beyond letters, digits " "and . _ -, or other elements) that a re-write from here would lose: %s. Manage them with boto3 (https://lakehousebox.com/docs/lifecycle/), or pass " "--replace-all to drop them." % (len(blocked), ", ".join(r.get("id") or "?" for r in blocked)), EXIT_USAGE) for r in current: if r.get("id") == rule["id"]: continue kept.append({k: r.get(k) for k in ("id", "prefix", "expire_days", "expire_date", "abort_incomplete_multipart_days", "enabled") if r.get(k) is not None}) out = request(args, "PUT", "/v1/catalogs/%s/lifecycle" % cat, {"rules": kept + [rule]}) _emit_lifecycle(args, out, "Set" if not kept else "Set (%d rule%s kept)" % (len(kept), "" if len(kept) == 1 else "s")) def cmd_lifecycle_get(args): q = "?include_xml=true" if args.xml else "" out = request(args, "GET", "/v1/catalogs/%s/lifecycle%s" % (urllib.parse.quote(resolve_catalog(args)), q)) if args.xml and not _want_json(args): print(out.get("xml") or "(no lifecycle configuration)") return _emit_lifecycle(args, out, "Configured" if out.get("configured") else "None configured") def cmd_lifecycle_clear(args): ref = resolve_catalog(args) _confirm_irreversible(args, "Remove every lifecycle rule of catalog %s" % ref) out = request(args, "DELETE", "/v1/catalogs/%s/lifecycle" % urllib.parse.quote(ref)) if _want_json(args): print_json(out) return print("Cleared %d lifecycle rule%s on %s (catalog %s)." % (out.get("rules_removed", 0), "" if out.get("rules_removed") == 1 else "s", out.get("bucket"), out.get("name") or _cid(out))) if not out.get("had_rules"): print("# nothing was configured") # --draft (#2338): a starting AGENTS.md built from what the catalog already records -- each table's description, its # columns and their docs (lhbox table document), its row count and last update -- in the sections docs/agent-setup.md # names, with a TODO wherever only a person or the agent that loaded the data knows the answer. Printed, never set: it is # edited first, then written with --set. CLI-only: GET /v1/tables?detail=true, then GET /v1/table per table (its columns). AGENTS_MD_MAX_BYTES = 64 * 1024 # what --set accepts (the API's limit) AGENTS_MD_DRAFT_COLUMNS_MAX = 50 # tables whose columns a draft lists, one request each; the rest by name def _md_cell(v): """A catalog value (another person's text) as one line of Markdown: no line or column break, no control character.""" return _visible(" ".join(str(v).split())).replace("|", "\\|") def _md_when(v): m = re.match(r"(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})", str(v)) return "%s %s UTC" % m.groups() if m else _md_cell(v) def _md_type(t): return t if isinstance(t, str) else (t or {}).get("type", "nested") if isinstance(t, dict) else str(t) def _agents_md_draft(args): ref = args.warehouse listing = request(args, "GET", "/v1/tables?" + urllib.parse.urlencode({"catalog": ref, "detail": "true"})) name = listing.get("catalog") or listing.get("warehouse") or ref tables = sorted(listing.get("tables") or [], key=lambda t: t.get("table") or "") columns = {} for t in tables[:AGENTS_MD_DRAFT_COLUMNS_MAX]: if t.get("error"): continue try: with _quiet(): d = request(args, "GET", "/v1/table?" + urllib.parse.urlencode( {"catalog": ref, "namespace": t.get("namespace"), "name": t.get("name")})) except _Refused: continue # (dropped since the listing, or unreadable: named without its columns) columns[t.get("table")] = d.get("schema") or [] text = _agents_md_render(name, tables, columns, len(tables) > AGENTS_MD_DRAFT_COLUMNS_MAX) size = len(text.encode("utf-8")) if args.json: print_json({"catalog": name, "warehouse_id": listing.get("warehouse_id"), "tables": len(tables), "tables_with_columns": len(columns), "bytes": size, "limit_bytes": AGENTS_MD_MAX_BYTES, "draft": text}) else: # the text itself, piped too (as --raw): `--draft > AGENTS.md`, edit, `--set AGENTS.md` is the round trip sys.stdout.write(text) if size > AGENTS_MD_MAX_BYTES: print("Note: this draft is %d bytes; --set takes at most %d. Keep the columns a reader needs." % ( size, AGENTS_MD_MAX_BYTES), file=sys.stderr) if sys.stdout.isatty() and not args.json: print("\nA draft, not set. Save it (--draft > AGENTS.md), replace the TODOs, then: lhbox catalog agents-md %s " "--set AGENTS.md" % name, file=sys.stderr) def _agents_md_render(name, tables, columns, capped=False): """The draft's Markdown: the sections docs/agent-setup.md asks for, filled from `tables` (GET /v1/tables?detail rows) and `columns` ({ns.table: GET /v1/table's schema}).""" cat = _md_cell(name) out = ["# %s: TODO what the data is, in one line" % cat, "", "" % cat, "", "## Where to start", "TODO: the one or two tables to read first, and the question each answers.", "", "## Structure"] if not tables: out += ["", "TODO: this catalog has no tables yet."] by_ns = {} for t in tables: by_ns.setdefault(t.get("namespace") or "", []).append(t) for ns, rows in by_ns.items(): out += ["", "### %s" % _md_cell(ns)] for t in rows: tn = _md_cell(t.get("table")) out += ["", "#### %s" % tn, "", _md_cell(t["doc"]) if t.get("doc") else 'TODO: one row per ... (lhbox table document %s.%s --doc "...")' % (cat, tn)] facts = [] if isinstance(t.get("row_count"), int): facts.append("{:,} rows".format(t["row_count"])) if isinstance(t.get("size_bytes"), (int, float)): facts.append(fmt_bytes(t["size_bytes"])) if facts: out += ["", " · ".join(facts)] cols = columns.get(t.get("table")) if cols: out += ["", "| column | type | description |", "|---|---|---|"] out += ["| %s | %s | %s |" % (_md_cell(c.get("name")), _md_cell(_md_type(c.get("type"))), _md_cell(c["doc"]) if c.get("doc") else "TODO") for c in cols] if capped: out += ["", "" % AGENTS_MD_DRAFT_COLUMNS_MAX] out += ["", "## How tables join", "TODO: which columns join which tables, and the joins that look right but are not."] shared = {} for tname, cols in columns.items(): for c in sorted({c.get("name") for c in cols if c.get("name")}): shared.setdefault(c, []).append(tname) joins = sorted(((c, ts) for c, ts in shared.items() if len(ts) > 1), key=lambda x: (-len(x[1]), x[0]))[:15] if joins: out += ["", "Columns with the same name in several tables (check each is a real join):", ""] out += ["- `%s`: %s" % (_md_cell(c), ", ".join(_md_cell(t) for t in sorted(ts))) for c, ts in joins] out += ["", "## Analytical caveats", "TODO: units and scales, how dates are stamped, codes and what null means, projections versus observations.", "", "## Freshness", "TODO: what refreshes each table (a sink, scheduled SQL, a manual import) and how often."] dated = [t for t in tables if t.get("last_updated")] if dated: out += ["", "| table | last updated (when drafted) |", "|---|---|"] out += ["| %s | %s |" % (_md_cell(t.get("table")), _md_when(t["last_updated"])) for t in dated] out += ["", "## Attribution", "TODO: the source, its licence, how to cite it.", ""] return "\n".join(out) # ---------------------------------------------------------------- AGENTS.md: the catalog's context for agents (research/39) # The object AGENTS.md at the root of the catalog's file bucket; GET/PUT/DELETE /v1/catalogs/{id}/agents-md. Reading prints # the owner's text under its label (JSON when piped, with source/trust); --set writes a file or stdin (write level, 64 KB, # audited), guarded by --base-sha256 when given; --remove deletes it. def cmd_catalog_agents_md(args): path = "/v1/catalogs/%s/agents-md" % urllib.parse.quote(resolve_catalog(args)) if args.set is not None and args.remove: die("--set and --remove are exclusive.", EXIT_USAGE) if args.draft and (args.set is not None or args.remove): die("--draft only prints a draft; write it with --set in a second command.", EXIT_USAGE) if args.draft: _agents_md_draft(args) return if args.remove: out = request(args, "DELETE", path) if _want_json(args): print_json(out) return print("Removed AGENTS.md from catalog %s (%s)." % (out.get("name") or _cid(out), (out.get("agents_md") or {}).get("s3_uri"))) return if args.set is not None: try: raw = sys.stdin.buffer.read() if args.set == "-" else open(args.set, "rb").read() except OSError as exc: die("Cannot read %s: %s" % (args.set, exc.strerror or exc), EXIT_ERROR) try: text = raw.decode("utf-8") except UnicodeDecodeError: die("AGENTS.md must be UTF-8 text; %s is not." % args.set, EXIT_ERROR) body = {"text": text} if args.base_sha256: body["base_sha256"] = None if args.base_sha256 == "none" else args.base_sha256 out = request(args, "PUT", path, body) if _want_json(args): print_json(out) return md = out.get("agents_md") or {} print("Wrote AGENTS.md to catalog %s: %s bytes, sha256 %s." % (out.get("name") or _cid(out), md.get("size"), md.get("sha256"))) print(" %s" % md.get("s3_uri")) if md.get("public_url"): print(" public: %s" % md.get("public_url")) return out = request(args, "GET", path) md = out.get("agents_md") or {} # --raw is asked for, so it wins over the piped default (only an explicit --json beats it): piped, it printed the # JSON envelope, and `--raw > AGENTS.md`, edit, `--set AGENTS.md` wrote that envelope into the catalog (2026-10-02) if args.raw and not args.json: sys.stdout.write(md.get("text") or "") return if _want_json(args): print_json(out) return if not md.get("present"): print("Catalog %s has no AGENTS.md. Write one: lhbox catalog agents-md %s --set AGENTS.md" % (out.get("name"), out.get("name"))) return print("# AGENTS.md of catalog %s, written by the catalog owner (%s)" % (out.get("name"), md.get("trust"))) print("# %s bytes, last changed %s, sha256 %s%s" % (md.get("size"), md.get("last_modified") or "?", md.get("sha256") or "-", ", TRUNCATED at 64 KB" if md.get("truncated") else "")) if md.get("public_url"): print("# public: %s" % md.get("public_url")) print() sys.stdout.write(_visible(md.get("text") or "", lines=True)) # --raw above stays byte-exact, for a file if not (md.get("text") or "").endswith("\n"): print() # ---------------------------------------------------------------- files: the catalog's file bucket (lhbox file put|get|ls|rm) # 2026-10-20 (the founder: agents upload files without installing the aws CLI or boto3). Every byte goes between this # machine and the store through URLs the API presigns (POST /v1/catalogs/{id}/blobs/upload for one PUT, the # …/blobs/multipart routes for a large file in parts, GET …/blobs/presign to read): the catalog's own key pair never # reaches this machine. The body is always sent with a Content-Length and never with a Content-Encoding (no aws-chunked # framing: research/88 §12.3, the store kept that token on every boto3 upload). FILE_MIB = 1024 * 1024 FILE_PART_DEFAULT_MIB = 64 # the API's plan; a file larger than one part goes up in parts FILE_PART_MIN_MIB = 5 FILE_PARALLEL_DEFAULT = 4 FILE_PART_RETRIES = 3 FILE_PUT_TIMEOUT = 600 # the content types this CLI names itself (mimetypes knows the rest; the store and the CDN type a published file by its # name either way, research/88 §12.2) FILE_TYPES = {".parquet": "application/vnd.apache.parquet", ".pmtiles": "application/vnd.pmtiles", ".geojson": "application/geo+json", ".geojsonl": "application/geo+json-seq", ".ndjson": "application/x-ndjson", ".jsonl": "application/x-ndjson", ".fgb": "application/vnd.flatgeobuf", ".gpkg": "application/geopackage+sqlite3", ".tif": "image/tiff", ".tiff": "image/tiff", ".csv": "text/csv", ".tsv": "text/tab-separated-values", ".md": "text/markdown", ".arrow": "application/vnd.apache.arrow.file", ".avro": "application/avro", ".orc": "application/octet-stream", ".duckdb": "application/octet-stream", ".mbtiles": "application/vnd.sqlite3", ".sqlite": "application/vnd.sqlite3", ".zarr": "application/octet-stream", ".gz": "application/gzip", ".zst": "application/zstd", ".bz2": "application/x-bzip2", ".xz": "application/x-xz", ".yaml": "application/yaml", ".yml": "application/yaml"} def _file_content_type(path): """A content type from the name: our table first, then mimetypes; a compressed file is its compression (data.csv.gz is application/gzip: what is stored is gzip bytes, never text/csv with an encoding).""" import mimetypes ext = os.path.splitext(path)[1].lower() if ext in FILE_TYPES: return FILE_TYPES[ext] guessed, encoding = mimetypes.guess_type(path, strict=False) if encoding: return "application/octet-stream" return guessed or "application/octet-stream" def _file_path(args, sub=""): return "/v1/catalogs/%s/blobs%s" % (urllib.parse.quote(resolve_catalog(args)), sub) # ---- the aws-shaped surface (0.6.63): `lhbox file cp|sync SRC DST` with one side lhbox:///, the aws flag # spellings (--metadata, --dryrun, --recursive, --exclude/--include), and a reason for the aws flags lhbox does not take FILE_SCHEME = "lhbox://" FILE_FOREIGN_SCHEMES = ("s3://", "s3a://", "s3n://") def _file_addr(raw): """(catalog, key) for lhbox:/// (catalog = name or id), None for anything else (a local path). An s3:// URL is refused: the bucket behind a catalog is the platform's name, not one a person or an agent addresses.""" low = raw.lower() if low.startswith(FILE_SCHEME): catalog, _, key = raw[len(FILE_SCHEME):].partition("/") if not catalog: die("%s names no catalog: write lhbox:///, e.g. lhbox://garden/public/tiles.pmtiles." % raw, EXIT_USAGE) return catalog, key if low.startswith(FILE_FOREIGN_SCHEMES): die("%s is an S3 URL. lhbox addresses a catalog's files as lhbox:/// (the catalog's name or id, " "e.g. lhbox://garden/public/tiles.pmtiles); the bucket behind it is the platform's, not a name to use here." % raw, EXIT_USAGE) return None def _file_set_catalog(args, catalog): """The catalog an address names becomes the command's --catalog; a different --catalog, or two addresses naming different catalogs, is a usage error rather than a guess.""" named = getattr(args, "warehouse", None) if named and named != catalog: die("Two catalogs named: %r and %r. Name one." % (named, catalog), EXIT_USAGE) args.warehouse = catalog def _file_key_arg(args, raw): """A KEY or PREFIX argument of put/get/ls/rm: a plain key, or lhbox:/// (which also names the catalog).""" if raw is None: return None addr = _file_addr(raw) if addr is None: return raw _file_set_catalog(args, addr[0]) return addr[1] def _file_folder(key): """A prefix taken as a folder: `data` means data/, never data2/ or database.csv (low review of #1662).""" return key if not key or key.endswith("/") else key + "/" class _FileFilter(argparse.Action): """--exclude / --include, kept in the order given (aws s3's rule: every file is in until a filter matches, and the LAST matching filter decides).""" def __call__(self, parser, namespace, values, option_string=None): items = list(getattr(namespace, self.dest, None) or []) items.append((self.const, values)) setattr(namespace, self.dest, items) def _file_wanted(args, rel): """Whether a path relative to the source root (a local folder, or a prefix in the catalog) passes the filters.""" import fnmatch keep = True for kind, pattern in getattr(args, "filters", None) or []: if fnmatch.fnmatchcase(rel, pattern): keep = kind == "include" return keep def _add_file_filters(sp): sp.add_argument("--exclude", dest="filters", action=_FileFilter, const="exclude", default=None, metavar="GLOB", help="leave out paths matching GLOB, relative to the source folder or prefix (* crosses /); " "--exclude and --include apply in order and the last match wins, as in aws s3") sp.add_argument("--include", dest="filters", action=_FileFilter, const="include", default=None, metavar="GLOB", help="take back paths matching GLOB after an --exclude (e.g. --exclude '*' --include '*.csv')") # aws s3 flags lhbox file does not take, and why: an argparse error that names the alternative instead of a bare # "unrecognized arguments" (an agent that knows aws s3 reaches for these first) _PUBLISH = ("a catalog's files have no per-file ACL: they are private to the catalog's grants, and a published catalog " "serves its public/ files to anyone (lhbox catalog publish)") _ENCRYPTED = "files are encrypted at rest by the platform; there is no per-file key or KMS choice to make" _NO_COPY = "there is no server-side copy between keys; lhbox file get the file, then lhbox file put it" AWS_FLAGS_UNSUPPORTED = { "--acl": _PUBLISH, "--grants": _PUBLISH, "--sse": _ENCRYPTED, "--sse-c": _ENCRYPTED, "--sse-c-key": _ENCRYPTED, "--sse-kms-key-id": _ENCRYPTED, "--storage-class": "a catalog has one storage class for all its data; there is none to choose", "--expires": ("there is no per-file expiry; files under a prefix are deleted after N days by a lifecycle rule: " "lhbox catalog lifecycle set --prefix PREFIX --expire-days N"), "--content-encoding": ("files are stored as the bytes you send: upload data.csv.gz as it is (typed application/gzip) " "and readers decompress it"), "--website-redirect": "a catalog's files have no redirects", "--request-payer": "the catalog's owner pays; there is nothing to pass", "--endpoint-url": ("lhbox talks to LakehouseBox's API itself and needs no storage endpoint (--url names another " "LakehouseBox API)"), "--region": "there is one region (Germany); there is nothing to pass", "--delete": ("lhbox file sync never deletes: remove what is no longer wanted with lhbox file rm KEY (or --recursive " "PREFIX; --dryrun lists first)"), "--size-only": "sync compares each file's size and ETag (its content), always", "--exact-timestamps": "sync compares each file's size and ETag (its content), always", "--follow-symlinks": "a symlinked file is uploaded as its target; symlinked folders are not walked", "--no-follow-symlinks": "a symlinked file is uploaded as its target; symlinked folders are not walked", "--metadata-directive": _NO_COPY, "--copy-props": _NO_COPY, "--source-region": _NO_COPY, "--page-size": "lhbox pages through listings itself", "--no-guess-mime-type": "the type comes from the file's name; --content-type sets one", } # accepted and ignored: progress is printed only on a terminal (or with --progress) and the output is already one result AWS_FLAGS_IGNORED = ("--quiet", "--only-show-errors", "--no-progress") class _AwsOnly(argparse.Action): def __init__(self, option_strings, dest, **kw): super().__init__(option_strings, dest=argparse.SUPPRESS, default=argparse.SUPPRESS, nargs="?", help=argparse.SUPPRESS) def __call__(self, parser, namespace, values, option_string=None): parser.error("%s is an aws s3 flag that lhbox file does not take: %s." % (option_string, AWS_FLAGS_UNSUPPORTED[option_string])) def _add_aws_flags(sp, ignored=AWS_FLAGS_IGNORED): for flag in AWS_FLAGS_UNSUPPORTED: sp.add_argument(flag, action=_AwsOnly) for flag in ignored: sp.add_argument(flag, dest="_aws_ignored_" + flag.strip("-").replace("-", "_"), action="store_true", help=argparse.SUPPRESS) def _file_meta_pairs(item): """One --meta/--metadata value: name=value, aws's shorthand a=1,b=2 (a comma starts a new pair only when name= follows, so note=a,b keeps its comma), or aws's JSON {"a": "1"}.""" text = item.strip() usage = ("--meta/--metadata takes name=value (several: a=1,b=2, or JSON {\"a\": \"1\"}; sent as x-amz-meta-), " "not %r." % item) if text.startswith("{"): try: obj = json.loads(text) except ValueError: die(usage, EXIT_USAGE) if not isinstance(obj, dict) or not obj: die(usage, EXIT_USAGE) return [(str(k), "" if v is None else str(v)) for k, v in obj.items()] pairs = [] for part in re.split(r",(?=[^,=]*=)", text): name, sep, value = part.partition("=") if not sep or not name.strip(): die(usage, EXIT_USAGE) pairs.append((name, value)) return pairs def _file_owner_body(args): """The owner's headers the API signs into the upload (research/88 §12): --cache-control, --content-disposition, --content-language, --meta/--metadata name=value.""" body = {} for flag in ("cache_control", "content_disposition", "content_language"): if getattr(args, flag, None): body[flag] = getattr(args, flag) meta = {} for item in getattr(args, "meta", None) or []: for name, value in _file_meta_pairs(item): meta[name.strip().lower()] = value if meta: body["metadata"] = meta return body class _FileSlice: """A byte range of a file, read in blocks, for an HTTP body with a known length (http.client reads it with read()): no whole part in memory, and the progress counter moves as the bytes go.""" def __init__(self, path, offset, length, progress=None): self._fh = open(path, "rb") self._fh.seek(offset) self._left = length self._progress = progress def read(self, n=-1): if self._left <= 0: return b"" n = self._left if n is None or n < 0 else min(n, self._left) chunk = self._fh.read(n) self._left -= len(chunk) if self._progress and chunk: self._progress(len(chunk)) return chunk def close(self): self._fh.close() def _storage_put(url, headers, path, offset, length, progress=None, timeout=FILE_PUT_TIMEOUT): """One PUT of a byte range to a presigned URL: (status, response headers, body bytes). The seam the tests replace. Content-Length always, no Content-Encoding and no Transfer-Encoding: the store gets the bytes as they are.""" body = _FileSlice(path, offset, length, progress) try: req = urllib.request.Request(url, data=body, method="PUT") for k, v in headers.items(): req.add_header(k, v) req.add_header("Content-Length", str(length)) try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, dict(r.headers), r.read() except urllib.error.HTTPError as e: return e.code, dict(e.headers or {}), e.read() finally: body.close() def _storage_get(url, timeout=120, headers=None): """A GET of a presigned URL (or, with headers, a signed one: the CDN's): the open response (the caller reads and closes it). The seam the tests replace.""" return urllib.request.urlopen(urllib.request.Request(url, headers=headers or {}, method="GET"), timeout=timeout) def _storage_refusal(status, body): """The store's XML error as (code, message).""" text = body.decode("utf-8", "replace") if isinstance(body, bytes) else str(body or "") code = re.search(r"([^<]*)", text) msg = re.search(r"([^<]*)", text) return (code.group(1) if code else "http_%d" % status), (msg.group(1) if msg else text[:200]) class _StorageFailed(Exception): def __init__(self, status, code, message, key): super().__init__(message) self.status, self.code, self.message, self.key = status, code, message, key def _put_with_retry(url_for, headers, path, offset, length, key, progress): """PUT a range, asking for a fresh URL and trying again on a 5xx or a broken connection (FILE_PART_RETRIES times): the ETag. A 4xx (a type the bucket refuses, over the quota, an expired URL) is final.""" last = None for attempt in range(FILE_PART_RETRIES): url = url_for() sent = [0] # this attempt's bytes: taken back from the counter if it fails def counted(n, sent=sent): sent[0] += n if progress: progress.add(n) try: status, rh, body = _storage_put(url, headers, path, offset, length, counted) except (urllib.error.URLError, OSError, http.client.HTTPException) as exc: if progress: progress.add(-sent[0]) last = _StorageFailed(0, "connection_lost", "%s: %s" % (type(exc).__name__, exc), key) time.sleep(min(2 ** attempt, 8)) continue if 200 <= status < 300: etag = {k.lower(): v for k, v in rh.items()}.get("etag", "") return etag.strip().strip('"') if progress: progress.add(-sent[0]) code, msg = _storage_refusal(status, body) last = _StorageFailed(status, code, msg, key) if status < 500: break time.sleep(min(2 ** attempt, 8)) raise last class _Progress: """Bytes sent, on stderr: when stderr is a terminal (and not --json), or with --progress (one line a few seconds).""" def __init__(self, args, total): self.on = bool(getattr(args, "progress", False)) or (sys.stderr.isatty() and not _want_json(args)) self.total, self.done, self.t0, self.last = total, 0, time.time(), 0.0 self.lock = threading.Lock() def add(self, n): if not self.on: return with self.lock: self.done += n now = time.time() if now - self.last >= (0.5 if sys.stderr.isatty() else 5) or self.done >= self.total: self.last = now rate = self.done / max(now - self.t0, 0.001) end = "\r" if sys.stderr.isatty() and self.done < self.total else "\n" sys.stderr.write(" %s of %s (%d%%), %s/s%s" % (fmt_bytes(self.done), fmt_bytes(self.total), 100 * self.done // max(self.total, 1), fmt_bytes(rate), end)) sys.stderr.flush() def _file_md5_etag(path, size, part_size, parts): """The ETag the store gives this file: md5 hex for one PUT, md5 of the parts' md5s + '-N' for N parts.""" with open(path, "rb") as fh: if not parts: h = hashlib.md5() for block in iter(lambda: fh.read(FILE_MIB), b""): h.update(block) return h.hexdigest() digests = b"" for _ in range(parts): h, left = hashlib.md5(), part_size while left > 0: block = fh.read(min(FILE_MIB, left)) if not block: break h.update(block) left -= len(block) digests += h.digest() return "%s-%d" % (hashlib.md5(digests).hexdigest(), parts) def _file_unchanged(path, size, remote, part_size): """True when the stored object has this file's size and the ETag this file would get.""" if not remote or remote.get("size") != size or not remote.get("etag"): return False etag = remote["etag"].strip('"') if "-" in etag: n = etag.rsplit("-", 1)[1] if not n.isdigit() or int(n) != max(1, -(-size // part_size)): return False return _file_md5_etag(path, size, part_size, int(n)) == etag return _file_md5_etag(path, size, part_size, 0) == etag def _file_same_as_remote(path, remote, part_mib=None): """_file_unchanged without knowing the part size the object was written with: --part-size, ours (64 MiB), then the common ones (aws CLI 8 MiB, the 5 MiB floor, 16, 32, 100, 128), only those that give the ETag's part count. A candidate that is wrong cannot match, so the worst case is a file transferred again, never one wrongly skipped.""" if not remote or not os.path.isfile(path): return False size = os.path.getsize(path) etag = (remote.get("etag") or "").strip('"') if remote.get("size") != size or not etag: return False if "-" not in etag: return _file_unchanged(path, size, remote, FILE_PART_DEFAULT_MIB * FILE_MIB) n = etag.rsplit("-", 1)[1] if not n.isdigit(): return False tried = set() for mib in ([part_mib] if part_mib else []) + [FILE_PART_DEFAULT_MIB, 8, 5, 16, 32, 100, 128]: part_size = mib * FILE_MIB if mib in tried or max(1, -(-size // part_size)) != int(n): continue tried.add(mib) if _file_unchanged(path, size, remote, part_size): return True return False def _upload_single(args, path, key, size, content_type, owner, progress): body = dict(owner, key=key) if content_type: body["content_type"] = content_type # the headers to send are the API's answer (exactly what it signed): the first URL comes with them, a retry asks again first = request(args, "POST", _file_path(args, "/upload"), body) urls = [first["url"]] def url_for(): return urls.pop() if urls else request(args, "POST", _file_path(args, "/upload"), body)["url"] etag = _put_with_retry(url_for, first.get("headers") or {}, path, 0, size, key, progress) return {"key": key, "size": size, "etag": etag or None, "method": "put", "parts": 1, "content_type": content_type or None} MULTIPART_COMPLETE_TRIES = 4 # a completion refused before any work (busy, 429, the store's error) is sent this often def _upload_multipart(args, path, key, size, content_type, owner, progress, part_size): body = dict(owner, key=key, size=size) if content_type: body["content_type"] = content_type up = request(args, "POST", _file_path(args, "/multipart"), body) upload_id = up["upload_id"] part_size = part_size or up.get("part_size") or FILE_PART_DEFAULT_MIB * FILE_MIB count = max(1, -(-size // part_size)) if count > (up.get("max_parts") or 10000): part_size = up["part_size"] count = max(1, -(-size // part_size)) import concurrent.futures stop = threading.Event() # set on the first failure: no part starts or retries after it def abort(): """True when the API answered the abort with a 2xx (the parts are freed); False when it refused or never answered.""" _SILENT.on = True # nothing printed: not the network (_SILENT), not a refusal (_quiet) try: with _quiet(): request(args, "POST", _file_path(args, "/multipart/abort"), {"key": key, "upload_id": upload_id}) return True except SystemExit: return False finally: _SILENT.on = False def url_for_part(n): def fetch(): if stop.is_set(): raise _StorageFailed(0, "cancelled", "the upload stopped at an earlier failure", key) # on a worker thread: an unreachable API raises silently (_SILENT), and the main thread reports it once _SILENT.on = True try: st, out = request_status(args, "POST", _file_path(args, "/multipart/parts"), {"key": key, "upload_id": upload_id, "part_numbers": [n]}) except SystemExit: raise _StorageFailed(0, "api_unreachable", "the API did not answer the request for a part URL", key) finally: _SILENT.on = False if st >= 400: err = (out or {}).get("error") or {} raise _StorageFailed(st, err.get("code") or "http_%d" % st, err.get("message") or "part URL refused", key) return out["parts"][0]["url"] return fetch def one(n): offset = (n - 1) * part_size length = min(part_size, size - offset) return n, _put_with_retry(url_for_part(n), {}, path, offset, length, key, progress) etags = {} pool = concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.parallel)) try: futures = [pool.submit(one, n) for n in range(1, count + 1)] for f in concurrent.futures.as_completed(futures): n, etag = f.result() # the first failure (or Ctrl-C) raises here etags[n] = etag except BaseException: # leaving a `with` block waited for every queued part: a refusal on part 1 still sent all the others before the # abort. Queued parts are dropped now; the ones in flight finish their current attempt, then the upload is aborted. stop.set() pool.shutdown(wait=True, cancel_futures=True) abort() raise pool.shutdown(wait=True) path_complete = _file_path(args, "/multipart/complete") held = {"key": key, "upload_id": upload_id, "upload_token": up.get("upload_token")} body = dict(held, parts=[{"part_number": n, "etag": etags[n]} for n in sorted(etags)]) # #2617: a completion the API refuses for good aborts the upload (its parts were kept, unreachable); one refused before # any work (busy, rate-limited, the store's error answer) is sent again a few times first, and one whose outcome is # unknown is never aborted: the envelope carries what completing it again needs for attempt in range(MULTIPART_COMPLETE_TRIES): _SILENT.on = True try: st, done = request_status(args, "POST", path_complete, body, timeout=SLOW_ADMIN_TIMEOUT) except SystemExit as e: if e.code != EXIT_SERVER: raise st, done = 0, None finally: _SILENT.on = False if done is None: die_json("completion_unknown", "The completion of %s was sent and its answer was lost or late: it may have " "completed." % key, EXIT_SERVER, outcome="unknown", remedy="List the key (lhbox file ls): a file of the expected size means it completed; otherwise send " "the completion again with this upload_id and upload_token (POST .../blobs/multipart/complete).", **held) err = done.get("error") if isinstance(done, dict) and isinstance(done.get("error"), dict) else {} code = err.get("code") again = st == 429 or code == "storage_error" or (st == 503 and code in _REFUSED_BEFORE_WORK) if not (again and attempt + 1 < MULTIPART_COMPLETE_TRIES): break time.sleep(max(2 ** (attempt + 1), int(err.get("retry_after_seconds") or 0))) if st >= 400: if 400 <= st < 500 and st != 429: # refused for good: nothing completed, so the parts are discarded, not kept unreachable if err.get("aborted") or abort(): err.update(aborted=True, completed=False) else: # #2797: the abort failed, the parts are still stored: the envelope says how to free them err.update(held, aborted=False, completed=False) else: # busy still, or the store may have finished it: kept, never aborted err.update(held) if again: err["completed"] = False if not (isinstance(done, dict) and done.get("error") is err): done = {"error": dict(err, code=code or "http_%d" % st)} _fail("POST", path_complete, st, done) return {"key": key, "size": done.get("size", size), "etag": done.get("etag"), "method": "multipart", "parts": count, "part_size": part_size, "content_type": content_type or None} ZARR_V2_METADATA = frozenset((".zarray", ".zattrs", ".zgroup", ".zmetadata")) def _file_plan(args): """[(local path, key, size)] for `file put`: one file (KEY, or KEY/ + its name, or its name), or a directory walked recursively (hidden files and folders skipped, except a Zarr v2 store's metadata files) under the prefix KEY/ (default: the directory's own name). --exclude / --include apply to the path relative to the directory (to the file's name for one file): filtered out is an empty plan, not an error.""" src = os.path.expanduser(args.sources) key = _file_key_arg(args, args.key_arg) if key is not None and key.startswith("/"): die("KEY is a key inside the catalog's files (data/file.csv, or lhbox:///data/file.csv), not an " "absolute path.", EXIT_USAGE) if not os.path.exists(src): die("%s does not exist." % args.sources, EXIT_ERROR) if os.path.isfile(src): name = os.path.basename(src) k = name if not key else (key + name if key.endswith("/") else key) return [(src, k, os.path.getsize(src))] if _file_wanted(args, name) else [] prefix = _file_folder(key if key is not None else os.path.basename(os.path.abspath(src))) plan, found = [], 0 for root, dirs, files in os.walk(src): dirs[:] = sorted(d for d in dirs if not d.startswith(".")) for f in sorted(files): if f.startswith(".") and f not in ZARR_V2_METADATA: # a Zarr v2 store's metadata is part of it (#2944) continue found += 1 full = os.path.join(root, f) rel = os.path.relpath(full, src).replace(os.sep, "/") if _file_wanted(args, rel): plan.append((full, prefix + rel, os.path.getsize(full))) if not found: die("%s holds no file to upload (hidden files are skipped)." % args.sources, EXIT_ERROR) return plan def _file_listing(args, prefix, delimiter=""): """Every object (and folder, with a delimiter) under a prefix, page by page: (objects, prefixes, bucket).""" objects, prefixes, token, bucket = [], [], None, None while True: q = {"prefix": prefix, "delimiter": delimiter, "max_keys": "1000"} if token: q["token"] = token page = request(args, "GET", _file_path(args, "?" + urllib.parse.urlencode(q))) bucket = page.get("bucket") objects += page.get("objects") or [] prefixes += page.get("prefixes") or [] token = page.get("next_token") if not page.get("truncated") or not token: return objects, prefixes, bucket # The gateway's file-type gate ((s3_file_types) in stack/gateway/Caddyfile.prod, research/53), applied to the whole plan # BEFORE a byte goes up: a folder holding one web page was refused at that file, half uploaded (#1757). A key passes when # its name is on the data list, or its body is under 100 kB and it is not a web page, script or program. The two patterns # are the gateway's own text; tests/test_walkthrough_2026_10_22.py fails when they drift from Caddyfile.prod. FILE_TYPES_ACCEPTED = (r"(?:.*\.(?:parquet|arrow|feather|ipc|avro|orc|puffin|stats|lance|text|duckdb|sqlite|nc|nc4|h5|hdf5|" r"he5|grib|grib2|grb|grb2|tif|tiff|vrt|ovr|msk|fgb|pmtiles|mbtiles|gpkg|glb|gltf|b3dm|pnts|i3dm|cmpt|" r"subtree|las|laz|pbf|shp|shx|dbf|prj|" r"cpg|sbn|sbx|qix|kml|kmz|gml|gpx|qml|sld|csv|tsv|txt|json|ndjson|jsonl|geojson|geojsonl|topojson|" r"yaml|yml|xml|md|sql|ipynb|log|crc|xlsx|xls|ods|pdf|jpg|jpeg|png|webp|heic|heif|zip|7z|tar|gz|tgz|" r"zst|bz2|xz)|.*\.zarr/(?:[^/]+/)*(?:\.zarray|\.zattrs|\.zgroup|\.zmetadata|zarr\.json|c|" r"c\.[0-9]+(?:\.[0-9]+)*|[0-9]+(?:\.[0-9]+)*))") FILE_TYPES_NEVER = (r"\.(?:html?|xhtml?|xht|shtml|mht|mhtml|js|mjs|cjs|svgz?|xsl|xslt|swf|wasm|php|aspx?|jsp|hta|exe|dll|" r"bat|cmd|ps1|sh|msi|apk|jar)$") FILE_TYPES_ACCEPTED_RE = re.compile(r"(?is)^" + FILE_TYPES_ACCEPTED + r"$") FILE_TYPES_NEVER_RE = re.compile(r"(?is)" + FILE_TYPES_NEVER) FILE_SMALL_MAX_BYTES = 99999 # the gateway: a Content-Length of at most 5 digits def _file_type_refused(key, size): """True when the gateway will answer 415 UnsupportedFileType for this key (a part upload is never small, and a file over 100 kB never goes up in parts of less than 5 MiB).""" if FILE_TYPES_ACCEPTED_RE.match(key): return False return size > FILE_SMALL_MAX_BYTES or bool(FILE_TYPES_NEVER_RE.search(key)) def cmd_file_put(args): plan = _file_plan(args) if args.part_size is not None and args.part_size < FILE_PART_MIN_MIB: die("--part-size is at least %d (MiB): every part but the last is at least 5 MiB." % FILE_PART_MIN_MIB, EXIT_USAGE) # AGENTS.md and the root _… keys are the platform's (#2946): the API refuses them, which ended a folder's upload # halfway, after the files before them in walk order -- e.g. a copy of a catalog's files, which brings _index/ along reserved = [(p, k, s) for p, k, s in plan if _file_reserved(k)] if reserved and not getattr(args, "skip_refused", False): keys = [k for _, k, _ in reserved] die_json("reserved_key", "%d file%s %s the platform's (AGENTS.md and the keys starting with _ at the catalog's " "root): %s; nothing was uploaded." % (len(keys), "" if len(keys) == 1 else "s", "is" if len(keys) == 1 else "are", ", ".join(keys[:10]) + (" and %d more" % (len(keys) - 10) if len(keys) > 10 else "")), EXIT_ERROR, keys=keys, uploaded=[], outcome="not_sent", remedy="--skip-refused uploads the rest and lists these as skipped; --exclude leaves them out. A " "catalog's AGENTS.md is set with lhbox catalog agents-md --set FILE.") reserved_keys = {k for _, k, _ in reserved} refused = [(p, k, s) for p, k, s in plan if k not in reserved_keys and _file_type_refused(k, s)] if refused and not getattr(args, "skip_refused", False): keys = [k for _, k, _ in refused] die_json("unsupported_file_type", "%d file%s %s not a type a catalog's files accept: %s; nothing was uploaded." % (len(keys), "" if len(keys) == 1 else "s", "is" if len(keys) == 1 else "are", ", ".join(keys[:10]) + (" and %d more" % (len(keys) - 10) if len(keys) > 10 else "")), EXIT_ERROR, keys=keys, uploaded=[], outcome="not_sent", remedy="--skip-refused uploads the rest and lists these as skipped; --exclude leaves them out. The " "catalog's files take data formats (web pages, scripts and programs never): " "https://lakehousebox.com/docs/files/ lists them.") refused_keys = {k for _, k, _ in refused} plan = [x for x in plan if x[1] not in refused_keys and x[1] not in reserved_keys] owner = _file_owner_body(args) part_size = (args.part_size or FILE_PART_DEFAULT_MIB) * FILE_MIB remote = {} if args.skip_unchanged and plan: common = os.path.commonprefix([k for _, k, _ in plan]) common = common[:common.rfind("/") + 1] if len(plan) > 1 else plan[0][1] objects, _, _ = _file_listing(args, common) remote = {o["key"]: o for o in objects} uploaded, t0 = [], time.time() skipped = ([{"key": k, "size": s, "reason": "not a type a catalog's files accept (--skip-refused)"} for _, k, s in refused] + [{"key": k, "size": s, "reason": "the platform's key (--skip-refused)"} for _, k, s in reserved]) refused, refused_keys = refused + reserved, refused_keys | reserved_keys total = sum(s for p, k, s in plan) progress = _Progress(args, total) for path, key, size in plan: if args.skip_unchanged and _file_same_as_remote(path, remote.get(key), args.part_size): skipped.append({"key": key, "size": size, "reason": "unchanged (same size and ETag)"}) progress.add(size) continue ctype = args.content_type or _file_content_type(path) if args.dry_run: uploaded.append({"key": key, "size": size, "content_type": ctype, "method": "multipart" if size > part_size else "put"}) continue if progress.on: sys.stderr.write("%s -> %s (%s)\n" % (path, key, fmt_bytes(size))) try: if size > part_size: uploaded.append(_upload_multipart(args, path, key, size, ctype, owner, progress, args.part_size and part_size)) else: uploaded.append(_upload_single(args, path, key, size, ctype, owner, progress)) except _StorageFailed as exc: die_json("storage_refused" if exc.status else "connection_lost", "%s: the upload was refused (%s %s): %s" % (exc.key, exc.status or "no answer", exc.code, exc.message), exit_code_for(exc.status) if exc.status else EXIT_SERVER, key=exc.key, status=exc.status, storage_code=exc.code, uploaded=[u["key"] for u in uploaded], outcome="failed", remedy=_storage_remedy(exc)) out = {"catalog": catalog_arg(args) or args.warehouse, "uploaded": uploaded, "skipped": skipped, "count": len(uploaded), "bytes": sum(u["size"] for u in uploaded), "seconds": round(time.time() - t0, 2), "dry_run": bool(args.dry_run)} if owner: out["headers"] = sorted(owner) if _want_json(args): print_json(out) return _table(uploaded, ["key", "size", "method", "parts", "etag"] if not args.dry_run else ["key", "size", "method", "content_type"]) unchanged = len(skipped) - len(refused) print("%s %d file%s, %s in %.1f s%s%s." % ("Would upload" if args.dry_run else "Uploaded", len(uploaded), "" if len(uploaded) == 1 else "s", fmt_bytes(out["bytes"]), out["seconds"], "; %d unchanged, skipped" % unchanged if unchanged else "", "; %d not accepted, skipped: %s" % (len(refused), ", ".join(sorted(refused_keys))) if refused else "")) def _storage_remedy(exc): if exc.code == "UnsupportedFileType" or exc.status == 415: return "The catalog's files take data formats: https://lakehousebox.com/docs/files/ lists them." if exc.status == 403: return ("The store refused the write: over the storage limit (lhbox usage) or the link expired; re-run, and " "check lhbox usage if it repeats.") if exc.status == 0 or exc.status >= 500: return "Nothing was kept of the file that failed (a multipart upload is aborted). Safe to re-run; --skip-unchanged skips what arrived." return "Fix what the store names, then re-run (--skip-unchanged skips the files already uploaded)." def _file_local_target(dest, key): """Where one downloaded file goes: DEST as given, inside DEST when it is a folder (or ends with /, created), or the key's own name here.""" name = key.rsplit("/", 1)[-1] if dest is None: return name dest = os.path.expanduser(dest) if os.path.isdir(dest): return os.path.join(dest, name) if dest.endswith("/") or dest.endswith(os.sep): os.makedirs(dest, exist_ok=True) return os.path.join(dest, name) return dest FILE_EDGE_TIMEOUT = 15 # seconds: a network that drops the CDN's traffic costs this once, then the storage answers FILES_LINK_FRESH_S = 600 # seconds: a storage link older than this is asked for again before use (it lives 900 s) _file_edge_unreachable = [] # set once the CDN could not be reached: the rest of this run reads the storage at once _PLAIN_MD5_RE = re.compile(r"^[0-9a-f]{32}$") # a single-part upload's ETag is the MD5 of its bytes def _file_edge_open(args, edge): """The file through the CDN when the catalog has edge caching on (the presign answer's `edge`: the file's address at the CDN and a credential to sign it with, SigV4), or None: no edge, --no-edge, or any refusal or connection failure, and the caller reads the storage link it already has (an older server, a network that cannot reach the CDN).""" if getattr(args, "no_edge", False) or _file_edge_unreachable or not isinstance(edge, dict): return None if not all(isinstance(edge.get(k), str) and edge.get(k) for k in ("url", "access_key_id", "secret_access_key")): return None if not edge["url"].startswith("https://"): return None try: headers = _sigv4_headers("GET", edge["url"], edge["access_key_id"], edge["secret_access_key"]) return _storage_get(edge["url"], timeout=FILE_EDGE_TIMEOUT, headers=headers) except urllib.error.HTTPError as e: e.close() return None except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError): _file_edge_unreachable.append(True) return None class _EdgeBroke(Exception): """The CDN's transfer broke before anything reached stdout (a file's partial copy is discarded): read the storage.""" class _EdgeStale(Exception): """The CDN's copy is not the storage's current file (_file_edge_check): read the storage.""" class _LocalWriteFailed(Exception): """Writing the download HERE failed (no folder can be made, a read-only place, a full disk): not the network (#2428).""" class _local_errors: """`with _local_errors():` an OSError inside is this machine's, raised as _LocalWriteFailed (on=False: left as is).""" def __init__(self, on=True): self.on = on def __enter__(self): return self def __exit__(self, kind, exc, tb): if self.on and isinstance(exc, OSError): raise _LocalWriteFailed(exc) from exc return False def _file_store_version(url): """The ETag of the file the storage holds now (quotes off), from a one-byte read of its presigned link (a GET link: no HEAD), or None when it does not say (an empty file answers 416 with the headers still naming it).""" try: r = _storage_get(url, timeout=30, headers={"Range": "bytes=0-0"}) h = r.headers r.close() except urllib.error.HTTPError as e: h = e.headers if e.code == 416 else None e.close() except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError): return None return ((h.get("ETag") or "").strip().strip('"') or None) if h is not None else None def _file_edge_check(etag, to_stdout): """The check a CDN copy passes before it is kept (research/100: the CDN is kept fresh by purges a second or so after a change, and bunny can serve a file overwritten in place mixed from two versions until then), against the ETag the storage gave just before the download (high review of #1939, 2, 5, 6: never a listing's, never a clock): a single upload's MD5 must be the bytes' MD5; a multipart upload's ETag must be what the bytes give for a common part size (_file_same_as_remote; an unknown part size reads the storage). -> check(md5 hex, path, size) -> ok?, or None when no check is possible (no ETag; a multipart file to stdout, where the bytes cannot be read again): read the storage.""" if not etag or not (_PLAIN_MD5_RE.match(etag) or re.match(r"^[0-9a-f]{32}-[0-9]{1,5}$", etag)): return None if _PLAIN_MD5_RE.match(etag): return lambda md5hex, path, size: md5hex == etag if to_stdout: return None return lambda md5hex, path, size: _file_same_as_remote(path, {"size": size, "etag": etag}) def _file_download(args, key, target, progress_on=True, etag=None): """GET one file into target (None = stdout), written whole or not at all (a temporary file beside it, renamed at the end): {key, path, bytes, sha256}. Through the CDN when the catalog has edge caching on (_file_edge_open), checked against the storage's current ETag before it is kept (_file_edge_check); otherwise, or when the CDN's transfer breaks before a byte reached stdout, or its copy is not the current file, through the presigned storage link (asked again when the first one may have expired). etag: unused since 0.6.91 (a listing's ETag can be older than the file).""" query = {"key": key} if not getattr(args, "no_edge", False): query["edge_auto"] = "2" # this CLI checks the CDN's copy itself (blobs.presign_blob) asked = time.time() out = request(args, "GET", _file_path(args, "/presign?" + urllib.parse.urlencode(query))) check = None if isinstance(out.get("edge"), dict) and not getattr(args, "no_edge", False) and not _file_edge_unreachable: check = _file_edge_check(_file_store_version(out["url"]), target is None) resp = _file_edge_open(args, out.get("edge")) if check else None if resp is not None: try: return _file_write(args, key, target, resp, progress_on, from_edge=True, check=check) except (_EdgeBroke, _EdgeStale) as e: # this file only (a file changed mid-copy breaks the CDN's transfer too: second high review of #1907, 6) if progress_on and target is not None and (sys.stderr.isatty() or getattr(args, "progress", False)): sys.stderr.write("%s: %s; downloading from the storage\n" % ( key, "the CDN's copy is not the current file" if isinstance(e, _EdgeStale) else "the CDN's transfer broke")) if time.time() - asked > FILES_LINK_FRESH_S: # a long CDN download may have outlived the storage link (15 minutes): a new one (high review of #1939, 2) out = request(args, "GET", _file_path(args, "/presign?" + urllib.parse.urlencode({"key": key}))) try: resp = _storage_get(out["url"]) except urllib.error.HTTPError as e: code, msg = _storage_refusal(e.code, e.read()) die_json("not_found" if e.code == 404 else "storage_refused", "%s: the store answered %s %s: %s" % (key, e.code, code, msg), exit_code_for(e.code), key=key, status=e.code, storage_code=code) except (urllib.error.URLError, OSError) as e: die_json("connection_lost", "%s: %s" % (key, e), EXIT_SERVER, key=key, outcome="failed", remedy="A read changes nothing: safe to retry.") return _file_write(args, key, target, resp, progress_on) def _file_write(args, key, target, resp, progress_on, from_edge=False, check=None): """resp's body into target (None = stdout), whole or not at all. A body shorter than its Content-Length is a broken transfer. from_edge: a break raises _EdgeBroke (the caller reads the storage) unless bytes already reached stdout. check(md5 hex, path, size) -> bool, before the file is kept: False discards it and raises _EdgeStale (on stdout, where the bytes are gone already, the command fails instead, saying so).""" to_stdout = target is None h, m, n = hashlib.sha256(), hashlib.md5(), 0 total = int(resp.headers.get("Content-Length") or 0) progress = _Progress(args, total) if not to_stdout and progress_on else None sink = sys.stdout.buffer if to_stdout else None tmp = None try: if not to_stdout: folder = os.path.dirname(os.path.abspath(target)) with _local_errors(): os.makedirs(folder, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix=".lhbox-get.", dir=folder) sink = os.fdopen(fd, "wb") for block in iter(lambda: resp.read(FILE_MIB), b""): with _local_errors(not to_stdout): sink.write(block) h.update(block) m.update(block) n += len(block) if progress: progress.add(len(block)) if total and n != total: raise http.client.IncompleteRead(b"", total - n) if not to_stdout: with _local_errors(): sink.close() else: sink.flush() if check is not None and not check(m.hexdigest(), tmp, n): if not to_stdout: raise _EdgeStale() die_json("edge_copy_stale", "%s: the CDN's copy was not the file the storage holds (it changed just before or " "while it was read); what was written out is not that file." % key, EXIT_SERVER, key=key, outcome="failed", remedy="Run the same command again, or with --no-edge to read the storage directly.") if not to_stdout: with _local_errors(): os.replace(tmp, target) tmp = None except _LocalWriteFailed as e: # the same write fails the same way again: not exit 5's "safe to retry", and never a second download (#2428) err = e.args[0] die_json("local_write_failed", "%s: could not write %s here (%s)." % (key, target, getattr(err, "strerror", None) or err), EXIT_ERROR, key=key, path=target, outcome="failed", remedy="Nothing was downloaded to it. Free some space, or choose a destination you can write.") except (urllib.error.URLError, OSError, http.client.HTTPException) as e: if from_edge and (not to_stdout or n == 0): raise _EdgeBroke() from e die_json("connection_lost", "%s: the download broke after %d bytes (%s)." % (key, n, e), EXIT_SERVER, key=key, outcome="failed", remedy="A read changes nothing: safe to retry.") finally: resp.close() if tmp and os.path.exists(tmp): if not to_stdout and sink is not None and not sink.closed: sink.close() os.unlink(tmp) return {"key": key, "path": target, "bytes": n, "sha256": h.hexdigest()} def cmd_file_get(args): key = _file_key_arg(args, args.key) dest = args.output if args.dest is not None: if dest is not None and dest != args.dest: die("Two destinations: %s and -o %s. Name one." % (args.dest, dest), EXIT_USAGE) dest = args.dest if not key or key.endswith("/"): die("%s is a folder: name a file, or download the folder with lhbox file cp lhbox:///%s DIR " "--recursive (lhbox file ls %s lists it)." % (key or "the root", key, key), EXIT_USAGE) if dest == "-": _file_download(args, key, None) return emit(args, _file_download(args, key, _file_local_target(dest, key))) def _file_safe_target(root, rel, key): """root/rel for a downloaded key, refused when the key would land outside root (a key holding .. or starting with /): a catalog's keys are other people's input to this machine's file system.""" parts = [p for p in rel.split("/") if p not in ("", ".")] if not parts or ".." in parts or rel.startswith("/"): die_json("unsafe_key", "%s: this key would be written outside %s; nothing was downloaded." % (key, root), EXIT_ERROR, key=key, remedy="Download it alone with lhbox file get KEY -o PATH, or leave it out with " "--exclude.") target = os.path.join(root, *parts) base = os.path.abspath(root) if os.path.commonpath([base, os.path.abspath(target)]) != base: die_json("unsafe_key", "%s: this key would be written outside %s; nothing was downloaded." % (key, root), EXIT_ERROR, key=key) return target def _file_refuse_clashes(root, jobs): """Two keys this file system cannot hold side by side (data/a//b and data/a/b to one path, or data/run as a file and data/run/x under it) are refused before the first byte, never one written over the other.""" seen = {} for o, target in jobs: seen.setdefault(os.path.normcase(os.path.abspath(target)), []).append(o["key"]) base = os.path.normcase(os.path.abspath(root)) for path, keys in seen.items(): clash = keys[1:2] parent = os.path.dirname(path) while not clash and parent != base and len(parent) > len(base): clash = seen.get(parent, [])[:1] parent = os.path.dirname(parent) if clash: die_json("local_path_clash", "%s and %s would be written to the same local path in %s (or one where " "the other needs a folder); nothing was downloaded." % (clash[0], keys[0], root), EXIT_ERROR, keys=[clash[0], keys[0]], remedy="Download one of them alone with lhbox file get KEY -o PATH, " "or leave it out with --exclude.") def _file_download_tree(args, key, dest, sync): """A prefix (taken as a folder) to a local directory, relative paths kept; with sync, a local file with the same size and ETag is skipped. Every target is checked before the first byte is fetched.""" prefix = _file_folder(key) objects, _, _ = _file_listing(args, prefix) objects = [o for o in objects if not o["key"].endswith("/")] if not objects and not sync: die("Nothing under %s in catalog %s: nothing was downloaded (one file is copied without --recursive; " "lhbox file ls lists the files)." % (prefix or "the root", catalog_arg(args)), EXIT_NOTFOUND) root = os.path.expanduser(dest) if os.path.exists(root) and not os.path.isdir(root): die("%s is a file: a folder is downloaded into a directory." % dest, EXIT_USAGE) jobs = [] for o in objects: rel = o["key"][len(prefix):] if _file_wanted(args, rel): jobs.append((o, _file_safe_target(root, rel, o["key"]))) _file_refuse_clashes(root, jobs) downloaded, skipped, t0 = [], [], time.time() for o, target in jobs: if sync and _file_same_as_remote(target, o): skipped.append({"key": o["key"], "path": target, "size": o.get("size"), "reason": "unchanged (same size and ETag)"}) continue if args.dry_run: downloaded.append({"key": o["key"], "path": target, "bytes": o.get("size")}) continue if sys.stderr.isatty() and not _want_json(args): sys.stderr.write("%s -> %s (%s)\n" % (o["key"], target, fmt_bytes(o.get("size")))) downloaded.append(_file_download(args, o["key"], target, progress_on=False, etag=o.get("etag"))) out = {"catalog": catalog_arg(args), "prefix": prefix, "path": root, "downloaded": downloaded, "skipped": skipped, "count": len(downloaded), "bytes": sum(d.get("bytes") or 0 for d in downloaded), "seconds": round(time.time() - t0, 2), "dry_run": bool(args.dry_run)} if _want_json(args): print_json(out) return _table(downloaded, ["key", "path", "bytes"]) print("%s %d file%s, %s in %.1f s%s." % ("Would download" if args.dry_run else "Downloaded", len(downloaded), "" if len(downloaded) == 1 else "s", fmt_bytes(out["bytes"]), out["seconds"], "; %d unchanged, skipped" % len(skipped) if skipped else "")) def _file_transfer(args, sync): """`file cp` and `file sync`: exactly one side is lhbox:///. Up = `file put` (sync adds --skip-unchanged); down = `file get` for one key, the tree for a folder (a key ending in /, --recursive, or sync).""" verb = "sync" if sync else "cp" src, dst = _file_addr(args.src), _file_addr(args.dst) example = "lhbox file %s ./data lhbox://garden/public/ (up) or lhbox file %s lhbox://garden/public/ ./data (down)" % (verb, verb) if src and dst: die("Both sides are catalog addresses: one side of lhbox file %s is a local path (there is no copy between " "catalogs or keys: get, then put). E.g. %s." % (verb, example), EXIT_USAGE) if not src and not dst: die("Neither side is a catalog address: write the catalog side as lhbox:/// (the " "catalog's name or id), e.g. %s." % example, EXIT_USAGE) if args.src == "-": die("lhbox file %s reads files, not stdin: write it to a file first." % verb, EXIT_USAGE) if dst: _file_set_catalog(args, dst[0]) args.sources, args.key_arg = args.src, dst[1] args.skip_unchanged = bool(sync or args.skip_unchanged) return cmd_file_put(args) _file_set_catalog(args, src[0]) key = src[1] if sync or args.recursive or not key or key.endswith("/"): if args.dst == "-": die("A folder cannot go to stdout: name a directory.", EXIT_USAGE) return _file_download_tree(args, key, args.dst, sync) name = key.rsplit("/", 1)[-1] if not _file_wanted(args, name): emit(args, {"key": key, "path": None, "skipped": True, "reason": "left out by --exclude/--include"}) return if args.dst == "-": _file_download(args, key, None) return target = _file_local_target(args.dst, key) if args.dry_run: emit(args, {"key": key, "path": target, "dry_run": True}) return emit(args, _file_download(args, key, target)) def cmd_file_cp(args): _file_transfer(args, sync=False) def cmd_file_sync(args): _file_transfer(args, sync=True) def cmd_file_ls(args): prefix = _file_key_arg(args, args.prefix) or "" objects, prefixes, bucket = _file_listing(args, prefix, "" if args.recursive else "/") if _want_json(args): print_json({"catalog": catalog_arg(args), "bucket": bucket, "prefix": prefix, "recursive": bool(args.recursive), "objects": objects, "prefixes": prefixes, "count": len(objects) + len(prefixes), "bytes": sum(o.get("size") or 0 for o in objects)}) return rows = [{"key": p["prefix"], "size": "", "last_modified": ""} for p in prefixes] rows += [{"key": o["key"], "size": fmt_bytes(o.get("size")), "last_modified": o.get("last_modified") or ""} for o in objects] _table(rows, ["key", "size", "last_modified"], {"last_modified": "modified"}) def _confirm_file_rm(args, what): """file rm's own guard (2026-10-20, founder): asked [y/N] when a person is at a terminal on both ends; a script or an agent (no terminal) deletes as `aws s3 rm` does, with no --yes and no warning. --yes (or the old --confirm) skips the question. The add_yes verbs keep _confirm_irreversible.""" if getattr(args, "yes", False) or getattr(args, "confirm", None): return if sys.stdin.isatty() and sys.stdout.isatty() and not args.json: if _ask("%s? This cannot be undone. [y/N] " % what).strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was changed.", EXIT_USAGE) FILE_RESERVED_WHAT = "AGENTS.md and the keys starting with _ at the root are the platform's" FILE_RESERVED_NOTE = FILE_RESERVED_WHAT + ": lhbox file rm leaves them" def _file_reserved(key): """A key the API refuses to write or delete (control plane _files_writable_key): AGENTS.md (its own route) and the service area, keys starting with _ at the root (feed intake, indexes, probe files).""" return key == "AGENTS.md" or key.startswith("_") def cmd_file_rm(args): keys, kept = [], [] for raw in args.keys: k = _file_key_arg(args, raw) if args.recursive: # a folder, never a bare prefix: `rm -r data` must not take data2/ or database.csv (low review of #1662) prefix = _file_folder(k) objects, _, _ = _file_listing(args, prefix) for o in objects: if not _file_wanted(args, o["key"][len(prefix):]): continue # `rm -r lhbox://cat/` listed AGENTS.md and _sink/…: the first refusal ended the run halfway (kept if _file_reserved(o["key"]) else keys).append(o["key"]) else: keys.append(k) if not keys and kept: die("Nothing to delete under %s: %d file%s there %s (%s)." % ( ", ".join(args.keys), len(kept), "" if len(kept) == 1 else "s", "is" if len(kept) == 1 else "are", FILE_RESERVED_NOTE), EXIT_NOTFOUND) if not keys: die("Nothing under %s%s: nothing was deleted." % (", ".join(args.keys), " that passes --exclude/--include" if args.filters else ""), EXIT_NOTFOUND) catalog = resolve_catalog(args) if args.dry_run: out = {"catalog": catalog, "would_delete": keys, "count": len(keys), "dry_run": True} if kept: out.update(kept=kept, kept_note=FILE_RESERVED_NOTE) emit(args, out) return _confirm_file_rm(args, "Delete %d file%s from catalog %s (%s%s)" % ( len(keys), "" if len(keys) == 1 else "s", catalog, ", ".join(keys[:3]), ", …" if len(keys) > 3 else "")) # up to --parallel deletes in flight (perf #2729: one round trip each, strictly in turn, was minutes for a zarr store). # The first refusal stops new ones; those already sent finish and are reported exactly in deleted / not_deleted import concurrent.futures import itertools path_of = {k: _file_path(args, "?" + urllib.parse.urlencode({"key": k})) for k in keys} order = {} for i, k in enumerate(keys): order.setdefault(k, i) def one(k): # a worker thread: answers, never prints, never exits _SILENT.on = True try: return (k,) + tuple(request_status(args, "DELETE", path_of[k])) except SystemExit as exc: # unreachable, a timeout, a lost answer: reported below, once return k, None, exc finally: _SILENT.on = False width = max(1, args.parallel) done, failures = set(), [] todo = iter(keys) with concurrent.futures.ThreadPoolExecutor(max_workers=min(width, len(keys))) as pool: running = {pool.submit(one, k) for k in itertools.islice(todo, width)} while running: finished, running = concurrent.futures.wait(running, return_when=concurrent.futures.FIRST_COMPLETED) for f in finished: k, status, parsed = f.result() if status is None or status >= 400: failures.append((k, status, parsed)) else: done.add(k) if not failures: running |= {pool.submit(one, k) for k in itertools.islice(todo, len(finished))} deleted = [k for k in keys if k in done] # in key order, as before if failures: # the first failed key in key order is the one reported k, status, parsed = min(failures, key=lambda x: order[x[0]]) not_deleted = [x for x in keys if x not in done] if status is None: exc = parsed die_json("connection_lost", "%s: the API did not answer the delete (deleted %d of %d)" % (k, len(deleted), len(keys)), exc.code if isinstance(exc.code, int) else EXIT_SERVER, key=k, deleted=deleted, not_deleted=not_deleted, outcome="unknown", remedy="lhbox file ls shows what is left; re-run rm for the keys still there.") # a refusal partway used to end the run with no word of what was already gone if not (isinstance(parsed, dict) and isinstance(parsed.get("error"), dict)) and not ( status == 404 and isinstance(parsed, dict) and parsed.get("detail") == "Not Found"): detail = parsed.get("detail") if isinstance(parsed, dict) else None parsed = {"error": {"code": "http_%d" % status, "message": (detail if isinstance(detail, str) else json.dumps(detail or parsed))[:500]}} if isinstance(parsed.get("error"), dict): parsed["error"].update(key=k, deleted=deleted, not_deleted=not_deleted) _fail("DELETE", path_of[k], status, parsed) if _want_json(args): out = {"catalog": catalog_arg(args), "deleted": deleted, "count": len(deleted)} if kept: out.update(kept=kept, kept_note=FILE_RESERVED_NOTE) print_json(out) return print("Deleted %d file%s.%s" % (len(deleted), "" if len(deleted) == 1 else "s", " Left %d of the platform's (%s)." % (len(kept), ", ".join(kept[:3]) + (", …" if len(kept) > 3 else "")) if kept else "")) # ---------------------------------------------------------------- sinks: one HTTP intake per table (research/24) # platform/docs/ingest-sink.md. A producer without an engine POSTs JSON arrays to the sink's send route with a send-only # key; the platform commits them to the table on the sink's roll policy. The send key comes back from the API exactly # once and follows the uploader's discipline: a 0600 file (--save) or the terminal once (--show-key), never both by # accident, and without either flag the command stops BEFORE the API call. def save_sink_file(path, out): """What a producer needs, one JSON file, mode 0600 whether created or overwritten. An existing file of the SAME sink is updated, not replaced: `sink device-token --save` onto the file `sink create --save` wrote must keep the send key (the API cannot show it again; code review 2026-09-24). A file of another sink is refused.""" path = os.path.expanduser(path) entry = {} if os.path.exists(path): try: with open(path) as fh: entry = json.load(fh) except (OSError, ValueError): entry = {} if entry.get("sink_id") and out.get("sink_id") and entry["sink_id"] != out["sink_id"]: die("%s holds sink %s, not %s: choose another file (nothing was written; the new secret is in the answer only " "if --show-key was given)." % (path, entry["sink_id"], out["sink_id"]), EXIT_USAGE) entry.update({k: out.get(k) for k in ("sink_id", "name", "warehouse_id", "table", "send_url", "ingest_url", "send_key", "roll", "prefix", "bucket") if out.get(k) is not None}) for k in ("device_token", "device_url", "device_url_http"): # research/32 §2: the device route, when made if out.get(k): entry[k] = out[k] _write_json_0600(path, entry) # whole or not at all: it may hold a send key the API cannot show again (#2498) return path def _sink_file_writable(path, nothing): """--save's file can be written, checked BEFORE the API call (#2498): a folder that cannot be made, a read-only place. The file is opened without truncating (an existing one is left as it was) and a file this check made is removed.""" path = os.path.expanduser(path) existed = os.path.lexists(path) # a dangling symlink is not removed (its target is made, and kept) try: folder = os.path.dirname(path) if folder: os.makedirs(folder, exist_ok=True) os.close(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600)) if not existed: os.unlink(path) except OSError as e: die_json("save_path_not_writable", "%s cannot be written (%s). %s" % (path, e.strerror or e, nothing), EXIT_USAGE, path=path, remedy="Choose a file in a folder you can write.") def _save_sink_file_after(args, out, remedy): """save_sink_file once the API has answered: a write that still fails (a full disk) is one envelope naming the sink and what to do, never main()'s "a bug, re-run" (a re-run creates or rotates again; #2498).""" try: return save_sink_file(args.save, out) except OSError as e: if args.show_key: # the person asked to see it: the secret is printed below, once, and the file is not written print("Note: %s could not be written (%s); the secret is shown below, once." % (args.save, e.strerror or e), file=sys.stderr) return None die_json("sink_file_not_saved", "%s could not be written (%s); the secret the API answered was not shown and cannot " "be shown again." % (args.save, e.strerror or e), EXIT_ERROR, sink_id=out.get("sink_id"), name=out.get("name"), path=args.save, remedy=remedy) # the flags of one kind of sink that the other kind has no use for (#2950): refused before the API call, never dropped SINK_SEND_ONLY_FLAGS = (("--save", "save"), ("--show-key", "show_key"), ("--device", "device"), ("--require-field", "require_field"), ("--strip", "strip"), ("--preset", "preset"), ("--param", "param"), ("--mapping", "mapping"), ("--roll-seconds", "roll_seconds"), ("--roll-bytes", "roll_bytes"), ("--inactivity-seconds", "inactivity_seconds")) SINK_SQL_ONLY_FLAGS = (("--every", "every"), ("--offset", "offset"), ("--paused", "paused"), ("--create-table", "create_table"), ("--partition", "partition")) def _sink_flags_given(args, flags): return [flag for flag, attr in flags if getattr(args, attr, None) not in (None, False, [])] def cmd_sink_create(args): if getattr(args, "sql", None): given = _sink_flags_given(args, SINK_SEND_ONLY_FLAGS) if given: die("%s %s for a send sink (without --sql): a scheduled SQL sink has no send key, device route or roll " "policy. Nothing was created." % (", ".join(given), "is" if len(given) == 1 else "are"), EXIT_USAGE) return cmd_sink_create_sql(args) given = _sink_flags_given(args, SINK_SQL_ONLY_FLAGS) if given: die("%s %s for a scheduled SQL sink (with --sql): a send sink commits what producers send, on its roll policy. " "Nothing was created." % (", ".join(given), "is" if len(given) == 1 else "are"), EXIT_USAGE) if getattr(args, "engine", None): die("--engine is for a scheduled SQL sink (with --sql): a send sink runs no query.", EXIT_USAGE) for flag, attr in (("--mode", "mode"), ("--min-rows", "min_rows"), ("--replace-existing", "replace_existing")): if getattr(args, attr, None) is not None and getattr(args, attr) is not False: die("%s is for a scheduled SQL sink (with --sql): a send sink appends what producers send." % flag, EXIT_USAGE) if getattr(args, "format_version", None): die("--format-version is for the table a scheduled SQL sink creates (--sql with --create-table); a send sink " "feeds a table that exists (lhbox table create --format-version).", EXIT_USAGE) if not args.save and not args.show_key: die("The send key is shown once and belongs in no transcript: pass --save (written 0600, nothing printed) " "or --show-key (printed once). Nothing was created.", EXIT_USAGE) if args.save: # checked BEFORE the API call: a new sink's file is a new file. Refusing it afterwards (save_sink_file refuses # another sink's file) left a sink whose send key reached nobody (the TTN guide run on production, 2026-10-04); # any other content (an uploader's secret, notes) would have been overwritten. held = os.path.expanduser(args.save) if os.path.exists(held) and os.path.getsize(held) > 0: die("%s already exists and is not empty: a new sink's key goes to a new file (choose another, or remove it " "if it is a deleted sink's). Nothing was created." % args.save, EXIT_USAGE) _sink_file_writable(args.save, "Nothing was created.") body = {"name": args.name, "table": args.table, "warehouse": resolve_catalog(args)} if args.key is not None: body["key"] = _key_arg(args.key) for field in ("roll_seconds", "roll_bytes", "inactivity_seconds"): if getattr(args, field, None) is not None: body[field] = getattr(args, field) body.update(_device_body(args)) mapping = _mapping_arg(args) if mapping is not None: body["mapping"] = mapping out = request(args, "POST", "/v1/sinks", body) key = out["send_key"] secrets_shown = [key] + ([out["device_token"]] if out.get("device_token") else []) shown = dict(out) if args.save: shown = dict(out) if args.show_key else mask_secrets(out, secrets_shown) shown["saved_to"] = _save_sink_file_after(args, out, ( "The sink was created and its send key reached nobody: lhbox sink delete %s --yes, then create it again with " "--save ." % out.get("sink_id"))) if _want_json(args): print_json(shown) return roll = out.get("roll") or {} print("Sink %s created: table %s of catalog %s, every %s s (or %d MiB, or %d batches)." % (out["name"], out["table"], out.get("warehouse_name") or _cid(out), roll.get("seconds"), int(roll.get("bytes", 0)) // (1024 * 1024), int(roll.get("count", 0)))) print(" send to: POST %s" % out.get("send_url")) print(" headers: Authorization: Bearer Idempotency-Key: Content-Type: application/json") print(" body: a JSON array of objects, up to 16 MiB; rows that do not fit the schema land in %s" % (out.get("rejects") or {}).get("prefix")) if args.show_key: print(" send key: %s <- shown once%s" % (key, ("; saved to " + shown["saved_to"]) if shown.get("saved_to") else "")) else: print(" send key: saved to %s (not shown; the API cannot show it again)" % shown["saved_to"]) if out.get("device_token"): _print_device_urls(args, out, shown) if out.get("mapping"): m = out["mapping"] print(" mapping: %s (%d rule%s), applied at each roll; try it: lhbox sink test %s " % (m.get("preset") or "custom", m.get("rules") or 0, "" if m.get("rules") == 1 else "s", out["name"])) tc = out.get("table_changes") or {} if tc.get("add_column"): print(" first roll: adds %s and the metadata-retention properties" % tc["add_column"]) if tc.get("format_version"): print(" writes: format-version %s through %s%s" % (tc["format_version"], (tc.get("writer") or "").split(" ", 1)[0], ", partitioned by %s" % tc["partition"] if tc.get("partition") not in (None, "none") else "")) print(" cost: no IAM write, no commit until the first roll") if out.get("docs_hint"): print(" describe it: %s" % out["docs_hint"]) print("Send a file: lhbox sink send %s batch.json --send-key-file %s" % (out["sink_id"], args.save or "")) print("Watch it: lhbox sink get %s" % out["name"]) def _device_body(args): """--device, --require-field FIELD=VALUE (hashed HERE: only its SHA-256 reaches the API), --strip FIELD.""" body = {} if getattr(args, "device", False): body["device"] = True if getattr(args, "require_field", None): field, sep, value = args.require_field.partition("=") if not sep or not field or not value: die("--require-field takes FIELD=VALUE, e.g. PASSKEY=.", EXIT_USAGE) body["device_require"] = {"field": field, "equals_sha256": hashlib.sha256(value.encode()).hexdigest()} if getattr(args, "strip", None): body["device_strip"] = list(args.strip) return body def _mapping_arg(args): """--mapping FILE (a mapping document) or --preset NAME [--param K=V ...]; None when neither.""" params = {} for p in getattr(args, "param", None) or []: k, sep, v = p.partition("=") if not sep or not k: die("--param takes NAME=VALUE, e.g. WS=ws-01.", EXIT_USAGE) params[k] = v if getattr(args, "mapping", None): if getattr(args, "preset", None): die("Pass --mapping FILE or --preset NAME, not both.", EXIT_USAGE) doc = _file_arg(args.mapping, "--mapping", json_object=True, remedy="--mapping takes a mapping document, a JSON object (lhbox sink mapping --help).") if params: doc["params"] = {**(doc.get("params") or {}), **params} return doc if getattr(args, "preset", None): return {"preset": args.preset, **({"params": params} if params else {})} if params: die("--param goes with --preset or --mapping.", EXIT_USAGE) return None def _print_device_urls(args, out, shown): """The device URL once (the token is in it): the plain-HTTP one when the deployment has a device host, else HTTPS.""" print(" device route: POST %s%s" % (shown.get("device_url_http") or shown.get("device_url"), " <- shown once" if args.show_key else "")) print(" no header needed; form, JSON, NDJSON or CSV, up to 256 KiB") if out.get("device_url_http"): print(" the same path also answers over HTTPS on %s" % out["device_url"].split("/d/", 1)[0]) print(" the URL is the credential: %d characters for the device's server + path fields" % out.get("device_url_chars", 0)) if not args.show_key: print(" device token: saved to %s with the URL (not shown; the API cannot show it again)" % shown.get("saved_to")) def cmd_sink_device_token(args): """POST /v1/sinks/{id}/device-token (a new token, the old one refused at once) or, with --revoke, DELETE.""" if args.revoke: out = request(args, "DELETE", "/v1/sinks/%s/device-token" % urllib.parse.quote(args.sink)) if _want_json(args): print_json(out) return print("Sink %s has no device route any more; its send key still works." % out.get("name")) return if not args.save and not args.show_key: die("The device URL is a credential shown once: pass --save (written 0600) or --show-key. Nothing was changed.", EXIT_USAGE) if args.save and os.path.exists(os.path.expanduser(args.save)): # refuse a file of ANOTHER sink before the token is rotated, or the new token would be lost with the refusal try: with open(os.path.expanduser(args.save)) as fh: held = json.load(fh) except (OSError, ValueError): held = None if not isinstance(held, dict): # not a JSON object (notes, a list, unreadable): save_sink_file would replace it whole (#2501). An empty file # is a new one, as for `sink create --save` if os.path.getsize(os.path.expanduser(args.save)) > 0: die("%s already exists and is not a sink's file: choose another file. Nothing was changed." % args.save, EXIT_USAGE) held = {} # by id only: a name is unique among live sinks, so the file of a deleted same-name sink matches it too (#2206) sid = args.sink if held.get("sink_id") and sid != held["sink_id"] and not UUID_RE.match(sid or ""): sid = request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(args.sink)).get("sink_id") if held.get("sink_id") and sid != held["sink_id"]: die("%s holds sink %s (%s), not %s%s: choose another file. Nothing was changed." % (args.save, held.get("name"), held["sink_id"], args.sink, " (%s)" % sid if sid != args.sink else ""), EXIT_USAGE) if args.save: _sink_file_writable(args.save, "Nothing was changed.") out = request(args, "POST", "/v1/sinks/%s/device-token" % urllib.parse.quote(args.sink)) shown = dict(out) if args.save: shown = dict(out) if args.show_key else mask_secrets(out, [out["device_token"]]) shown["saved_to"] = _save_sink_file_after(args, out, ( "The token was rotated (the previous device URL is refused) and the new one reached nobody: lhbox sink " "device-token %s --save ." % out.get("sink_id"))) if _want_json(args): print_json(shown) return print("Sink %s: a new device token; the previous one, if any, is refused from now on." % out.get("name")) _print_device_urls(args, out, shown) def cmd_sink_mapping(args): """Without a change flag: the sink's mapping document. --preset/--mapping/--clear: PATCH it (validated against the table; applied from the next roll to every batch not yet rolled).""" mapping = _mapping_arg(args) if args.clear and mapping is not None: die("Pass --clear or a new mapping, not both.", EXIT_USAGE) if mapping is None and not args.clear: out = request(args, "GET", "/v1/sinks/%s?include_mapping=true" % urllib.parse.quote(args.sink)) doc = out.get("mapping_document") if _want_json(args) or doc is not None: print_json(doc) else: print("Sink %s has no mapping: records are cast to the table's columns as they arrive." % out.get("name")) return out = request(args, "PATCH", "/v1/sinks/%s" % urllib.parse.quote(args.sink), {"mapping": None if args.clear else mapping}) if _want_json(args): print_json(out) return m = out.get("mapping") if m: print("Sink %s: mapping version %s (%s, %d rules)." % (out.get("name"), m.get("mapping_version"), m.get("preset") or "custom", m.get("rules") or 0)) else: print("Sink %s: mapping removed." % out.get("name")) print("It applies from the next roll to every batch not yet rolled (%s waiting now)." % out.get("applies_to_pending_batches", 0)) def cmd_sink_test(args): """POST /v1/sinks/{id}/test: the device route's dry run with your own key. Nothing is stored.""" if args.file == "-": data = sys.stdin.buffer.read() else: data = _file_arg(args.file, "file", binary=True, remedy="Name the captured body to test, or - for stdin.") ctype = args.content_type or _guess_content_type(args.file, data) out = request(args, "POST", "/v1/sinks/%s/test" % urllib.parse.quote(args.sink), raw_body=data, content_type=ctype) if _want_json(args): print_json(out) return print("Dry run on sink %s (%s): %d record%s, nothing stored." % (args.sink, ctype, out.get("accepted", 0), "" if out.get("accepted") == 1 else "s")) if out.get("device_secret"): print(" pinned secret: %s" % ("matches" if out["device_secret"] == "ok" else "MISSING OR WRONG: the device route would answer 401")) if out.get("stripped"): print(" stripped: %s" % ", ".join(out["stripped"])) if out.get("mapping"): rows = out.get("rows") or [] print(" mapping: %s v%s -> %d row%s" % (out["mapping"].get("preset") or "custom", out["mapping"].get("mapping_version"), out.get("rows_total", len(rows)), "" if out.get("rows_total") == 1 else "s")) if rows: cols = list(rows[0].keys()) emit(args, rows[:args.limit], cols) for f in out.get("unknown_fields") or []: print(" no rule for: %s" % f) for r in out.get("rejects") or []: print(" rejected: record %s: %s%s" % (r.get("index"), r.get("reason"), (" (" + r["field"] + ")") if r.get("field") else "")) else: emit(args, out.get("records") or []) # ------------------------------------------------------------------ hosted agents (research/47) AGENT_RUN_DONE = ("succeeded", "failed", "limit_exceeded", "timeout", "needs_attention", "lost") def _agent_body(args, creating): body = {} if getattr(args, "prompt", None) is not None: body["prompt"] = _sql_text(args.prompt, "--prompt") cats = list(getattr(args, "catalog", None) or []) if cats or creating or getattr(args, "no_catalogs", False): body["read"] = cats if getattr(args, "state_key", None) or getattr(args, "no_state_keys", False): body["state_keys"] = list(args.state_key or []) if getattr(args, "topic", None): # its memory topics (#2460): note / resolve / flag_owner body["memory"] = {"topics": list(args.topic)} elif getattr(args, "no_topics", False): body["memory"] = None if getattr(args, "notify_owner", None) is not None: body["notify_owner"] = args.notify_owner if getattr(args, "artifacts", None) is not None: body["artifacts"] = args.artifacts if getattr(args, "run_seconds", None) is not None: body["run_seconds"] = args.run_seconds if getattr(args, "max_tool_calls", None) is not None: body["max_tool_calls"] = args.max_tool_calls if getattr(args, "model", None): body["model"] = args.model if getattr(args, "schedule", None): body["schedule"] = {"cron": args.schedule, "tz": args.tz or "UTC"} elif getattr(args, "tz", None): die("--tz goes with --schedule (the schedule is replaced whole: pass both).", EXIT_USAGE) if getattr(args, "no_schedule", False): body["schedule"] = None if getattr(args, "integration", None): body["integrations"] = [_integration_grant(args, spec) for spec in args.integration] elif getattr(args, "no_integrations", False): body["integrations"] = [] if getattr(args, "write", None): body["write"] = list(args.write) elif getattr(args, "no_writes", False): body["write"] = [] if getattr(args, "on_commit", None): body["on_commit"] = list(args.on_commit) elif getattr(args, "no_on_commit", False): body["on_commit"] = [] if getattr(args, "on_commit_if", None) is not None: body["on_commit_if"] = args.on_commit_if elif getattr(args, "no_on_commit_if", False): body["on_commit_if"] = None if getattr(args, "allow_host", None) or getattr(args, "host_credential", None): body["web"] = _web_body(args, keep_current=not creating and not args.allow_host) if getattr(args, "_agent_read_version", None): body["if_version"] = args._agent_read_version elif getattr(args, "no_web", False): body["web"] = None return body def _web_body(args, keep_current=False): """--allow-host HOST (repeat) and --host-credential HOST=INTEGRATION -> {allow_hosts, credentials}; a credential's host is allowed too, and an integration name is resolved to its id (the API takes ids). The API replaces web whole: with --allow-host the settings become exactly these; `keep_current` (--host-credential alone on an update) adds to the agent's current hosts and keys, replacing only the key of the same host (#2300: the guide's second step dropped the host the first allowed).""" for spec in args.host_credential or []: host, sep, ref = spec.partition("=") if not sep or not host.strip() or not ref.strip(): die("--host-credential is HOST=INTEGRATION (a web key: lhbox integration add NAME --web-key --host HOST " "--api-key-stdin).", EXIT_USAGE) web = {} if keep_current: now = request(args, "GET", _agent_path(args)) web = now.get("web") or {} args._agent_read_version = now.get("version") # the PATCH names it: a change saved since is a 409 (#2722) hosts = [h.strip().lower() for h in args.allow_host or web.get("allow_hosts") or [] if h.strip()] named = {spec.partition("=")[0].strip().lower() for spec in args.host_credential or []} creds = [{"host": c["host"], "integration_id": c["integration_id"]} for c in web.get("credentials") or [] if c.get("host") not in named] for spec in args.host_credential or []: host, _, ref = spec.partition("=") got = request(args, "GET", "/v1/integrations/%s" % urllib.parse.quote(ref.strip())) creds.append({"host": host.strip().lower(), "integration_id": got["integration_id"]}) if host.strip().lower() not in hosts: hosts.append(host.strip().lower()) return {"allow_hosts": hosts, "credentials": creds} def _integration_grant(args, spec): """--integration NAME_OR_ID:tool,tool -> {integration_id, tools}; a name is resolved to its id (the API takes ids).""" ref, sep, tools = spec.partition(":") names = [t.strip() for t in tools.split(",") if t.strip()] if not sep or not ref or not names: die("--integration is NAME:tool[,tool...] (e.g. github:search_issues,get_file_contents); " "`lhbox integration show NAME` lists its tools.", EXIT_USAGE) got = request(args, "GET", "/v1/integrations/%s" % urllib.parse.quote(ref.strip())) return {"integration_id": got["integration_id"], "tools": names} def _agent_path(args, tail=""): return "/v1/agents/%s%s" % (urllib.parse.quote(args.name), tail) def _print_agent(a): print("Agent %s (version %s)%s" % (a.get("name"), a.get("version"), ", PAUSED" if a.get("paused") else "")) print(" model: %s" % a.get("model")) print(" reads: %s" % (", ".join(a.get("read") or []) or "no catalog")) print(" notifies owner: %s" % ("yes" if a.get("notify_owner") else "no")) if "artifacts" in a: # an API from before agents published artifacts says nothing print(" artifacts: %s" % ("publishes and updates pages" if a.get("artifacts") else "no")) print(" state keys: %s" % (", ".join(a.get("state_keys") or []) or "none")) print(" memory topics: %s" % (", ".join((a.get("memory") or {}).get("topics") or []) or "none")) print(" run limit: %s s" % a.get("run_seconds") + (", %s tool calls" % a["max_tool_calls"] if a.get("max_tool_calls") else "")) print(" appends to: %s" % (", ".join(a.get("write") or []) or "no table")) if a.get("on_commit"): waits = {w.get("table"): w.get("waiting") for w in a.get("watching") or [] if isinstance(w, dict)} print(" runs on commit: %s" % ", ".join("%s%s" % (t, " (waiting: %s)" % waits[t] if waits.get(t) else "") for t in a["on_commit"])) if a.get("on_commit_if"): print(" only if: %s" % a["on_commit_if"]) last = a.get("condition_checked") or {} if last.get("outcome"): print(" last checked: %s, %s%s" % (last.get("at"), last["outcome"].replace("_", " "), ": %s %s" % (last.get("code"), last.get("message") or "") if last.get("code") else "")) if a.get("watch_debounce_until"): print(" next commit run: not before %s" % a["watch_debounce_until"]) web = a.get("web") or {} keyed = {c.get("host") for c in web.get("credentials") or []} print(" web hosts: %s" % (", ".join("%s%s" % (h, " (key)" if h in keyed else "") for h in web.get("allow_hosts") or []) or "none")) if a.get("subscribers") is not None: print(" subscribers: %s%s" % (a.get("subscribers"), " (you included)" if a.get("subscribed") else "")) key = a.get("this_key") if isinstance(key, dict): # what THIS key may do (you_created is about the person behind it) runs = "yes" if key.get("read_runs") else "no (%s)" % (key.get("runs_closed_because") or "not a manager") print(" this key: %s; reads its runs: %s" % ("manages it" if key.get("manage") else "does not manage it", runs)) ints = a.get("integrations") or [] print(" integrations: %s" % ("; ".join("%s (%s)" % (i.get("integration_id", "")[:8], ", ".join(i.get("tools") or [])) for i in ints) or "none")) sched = a.get("schedule") print(" schedule: %s" % (("%s (%s)" % (sched.get("cron"), sched.get("tz"))) if sched else "none (runs on demand)")) if sched: print(" next run: %s" % (a.get("next_run_at") or ("paused" if a.get("paused") else "none"))) if a.get("paused_reason"): print(" paused because: %s" % a["paused_reason"]) slot = a.get("last_slot") or {} if slot and slot.get("outcome") != "run": print(" last slot: %s %s (%s)" % (slot.get("slot"), slot.get("outcome"), slot.get("code"))) last = a.get("last_run") or {} if last: print(" last run: %s %s (%s)" % (str(last.get("run_id", ""))[:8], last.get("state"), last.get("created_at"))) mem = a.get("state") or {} if mem: print(" memory:") for k, v in sorted(mem.items()): print(" %-14s %s" % (k + ":", (v[:160] + ("..." if len(v) > 160 else "")).replace("\n", " "))) prompt = a.get("prompt") or "" print(" prompt: %s" % (prompt[:200] + ("..." if len(prompt) > 200 else "")).replace("\n", " ")) def _print_integration_review(out): """The API's integration_review (the high review of the M6 fix): attaching your integrations hands them to these instructions, so they are shown on stderr whatever the output mode (stdout stays the API's JSON when piped).""" rev = (out or {}).get("integration_review") if not rev: return name = out.get("name") or "NAME" lines = ["Your integrations now run these instructions -- read them:", ""] lines += [" " + l for l in (rev.get("prompt") or "").splitlines() or [""]] lines += ["", "It writes to: %s" % (", ".join(rev.get("write") or []) or "no table"), "It sends your web keys to: %s" % (", ".join(rev.get("web_credentials") or []) or "no host"), "If you did not write them, change them (lhbox agent update %s --prompt ...) or detach " "(--no-integrations). An agent another credential defined runs with your integrations only after you " "approve its definition: lhbox agent update %s --confirm-definition" % (name, name)] print("\n".join(lines), file=sys.stderr) def cmd_agent_create(args): body = _agent_body(args, creating=True) body["name"] = args.name if args.org: body["org_id"] = args.org out = request(args, "POST", "/v1/agents", body) _print_integration_review(out) if _want_json(args): print_json(out) return _print_agent(out) print("Run it now with: lhbox agent run %s --wait" % out.get("name")) def cmd_agent_list(args): out = request(args, "GET", "/v1/agents" + (("?org_id=" + urllib.parse.quote(args.org)) if args.org else "")) if _want_json(args): print_json(out) return a = out.get("allowance") or {} if a: print("Allowance %s: %s of %s tokens used (%s held), %s of %s runs today." % ( a.get("period"), a.get("tokens_used"), a.get("tokens_granted"), a.get("tokens_held"), a.get("runs_today"), a.get("runs_per_day"))) rows = [{"name": x.get("name"), "version": x.get("version"), "model": x.get("model"), "reads": ",".join(x.get("read") or []), "paused": x.get("paused"), "last_run": ((x.get("last_run") or {}).get("state"))} for x in out.get("agents") or []] emit(args, rows, ["name", "version", "model", "reads", "paused", "last_run"]) # ----- artifacts: pages an agent publishes for people (research/130, 132 slice B; platform/docs/user/artifacts.md) ARTIFACT_PAGE_EXT = ("html", "css", "js", "json", "geojson", "csv", "svg") ARTIFACT_ASSET_EXT = ("png", "jpg", "jpeg", "webp", "gif", "avif", "woff2", "parquet", "pmtiles", "mp4") ARTIFACT_CONTENT_TYPES = {"html": "text/html", "css": "text/css", "js": "text/javascript", "json": "application/json", "geojson": "application/geo+json", "csv": "text/csv", "svg": "image/svg+xml"} ARTIFACT_META = "artifact.json" # what `pull` writes beside the files and `publish` reads its defaults from ARTIFACT_STORED_ASSET = re.compile(r"^[0-9a-f]{64}\.[a-z0-9]{1,8}$") # the names the API takes (plane/artifacts.py _file_kind): a page file's path, at most three folders deep; an asset's name ARTIFACT_PAGE_PATH = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}(/[A-Za-z0-9][A-Za-z0-9._-]{0,99}){0,3}$") ARTIFACT_ASSET_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$") def _artifact_ext(name): return name.rsplit(".", 1)[-1].lower() if "." in name else "" def _artifact_plan(path): """What `lhbox artifact publish PATH` sends -> (page files [(path inside the version, local path)], assets [(local name, local path)], the folder's artifact.json or {}). PATH is one HTML file; a folder of page files with index.html in it; or an artifact's folder as `pull` writes it (page/ with index.html, assets/ beside it, artifact.json). Everything is decided before anything is sent: a file type an artifact does not hold stops here.""" pages, assets, meta, problem = _artifact_layout(path) if problem: die(problem["message"], EXIT_ERROR) return pages, assets, meta def _artifact_layout(path): """_artifact_plan without stopping -> (pages, assets, meta, the first problem {code, message, ...} or None): what `lhbox artifact check DIR` reports, in the words a publish of DIR would stop with.""" if os.path.isfile(path): return [("index.html", path)], [], {}, None if not os.path.isdir(path): return [], [], {}, {"code": "not_found", "message": "No file or folder at %s." % _shown_path(path)} meta = {} meta_file = os.path.join(path, ARTIFACT_META) if os.path.isfile(meta_file): try: with open(meta_file, encoding="utf-8") as fh: meta = json.load(fh) except (OSError, ValueError): return [], [], {}, {"code": "artifact_json_invalid", "message": "%s is not valid JSON." % _shown_path(meta_file)} if not isinstance(meta, dict): meta = {} root = os.path.join(path, "page") if os.path.isfile(os.path.join(path, "page", "index.html")) else path if not os.path.isfile(os.path.join(root, "index.html")): return [], [], meta, {"code": "no_index", "message": "No index.html in %s (nor in its page/ folder): an " "artifact's page starts there." % _shown_path(path)} assets_dir = os.path.join(path, "assets") if root == path and os.path.isdir(assets_dir): # a page file is served from the version's folder and the assets from beside it: ../assets/ return [], [], meta, {"code": "assets_beside_index", "message": "%s holds index.html and an assets/ folder side " "by side. Put the page's files in a page/ folder beside assets/, and refer to an asset as " "../assets/." % _shown_path(path)} pages, bad = [], [] for base, dirs, names in os.walk(root): dirs[:] = sorted(d for d in dirs if not d.startswith(".")) for name in sorted(names): if name.startswith(".") or (base == root and name in (ARTIFACT_META, "manifest.json")): continue rel = os.path.relpath(os.path.join(base, name), root).replace(os.sep, "/") ok = _artifact_ext(name) in ARTIFACT_PAGE_EXT and ARTIFACT_PAGE_PATH.match(rel) and len(rel) <= 200 if ok: pages.append((rel, os.path.join(base, name))) else: # named as the folder has it: page/x.mjs, assets/x.json bad.append((("page/" if root != path else "") + rel, os.path.join(base, name))) assets = [] if os.path.isdir(assets_dir): for name in sorted(os.listdir(assets_dir)): full = os.path.join(assets_dir, name) if name.startswith("."): continue # a folder inside assets/ is not skipped in silence: the page would refer to files that were never sent ok = os.path.isfile(full) and _artifact_ext(name) in ARTIFACT_ASSET_EXT and ARTIFACT_ASSET_NAME.match(name) if ok: assets.append((name, full)) else: bad.append(("assets/" + name + ("" if os.path.isfile(full) else "/"), full)) if bad: return [], [], meta, {"code": "file_type_refused", "files": [rel for rel, _ in bad], "message": "An artifact holds page files (%s; names of letters, digits, . _ -, at most " "three folders deep) and, directly in assets/, %s; these are neither: %s. Nothing was sent." % (", ".join("." + e for e in ARTIFACT_PAGE_EXT), ", ".join("." + e for e in ARTIFACT_ASSET_EXT), ", ".join(rel for rel, _ in bad[:8]) + (" and %d more" % (len(bad) - 8) if len(bad) > 8 else ""))} pages.sort(key=lambda f: (f[0] != "index.html", f[0])) return pages, assets, meta, None def _artifact_bytes(path): try: with open(path, "rb") as fh: return fh.read() except OSError as e: die("Cannot read %s: %s." % (_shown_path(path), e.strerror or e), EXIT_ERROR) def cmd_artifact_publish(args): """One HTML file is published in one call; a folder as a pending version, its files uploaded one by one (assets first: a page file that names `assets/` is sent with the name the asset is stored under), then published. Nothing shows until the last call answers.""" pages, assets, meta = _artifact_plan(args.page) artifact_id = args.artifact or (meta.get("artifact_id") if isinstance(meta.get("artifact_id"), str) else None) if args.no_catalogs and args.catalog: die("--no-catalogs and --catalog say opposite things: pass one of them.", EXIT_USAGE) # what the command line says wins over the folder's artifact.json: --no-catalogs too (a pulled page that no longer # reads a catalog would otherwise go on naming it) catalogs = [] if args.no_catalogs else args.catalog if args.catalog is not None else ( meta.get("catalogs") if isinstance(meta.get("catalogs"), list) else None) prev = None if catalogs is None and artifact_id: # the next version of a page reads what the version before it read, unless the command line says otherwise (#3128) prev = request(args, "GET", "/v1/artifacts/" + urllib.parse.quote(artifact_id, safe="")) prev = prev if isinstance(prev, dict) else {} refs = (prev.get("manifest") or {}).get("catalog_refs") if isinstance(prev.get("manifest"), dict) else None if isinstance(refs, list) and all(isinstance(r, dict) and (r.get("warehouse_id") or r.get("name")) for r in refs): # each by the id it was resolved to (two catalogs of one name never make the next version read another), # another organisation's public catalog by its /, as it was named catalogs = [r["name"] if r.get("public") and r.get("name") else r.get("warehouse_id") or r["name"] for r in refs] else: catalogs = prev.get("catalogs") if isinstance(prev.get("catalogs"), list) else None if catalogs is None: die("Name the catalogs the page reads: --catalog CATALOG (repeat), or --no-catalogs for a page that reads none.", EXIT_USAGE) body = {"catalogs": catalogs or []} if artifact_id: body["artifact_id"] = artifact_id title = args.title or (None if artifact_id else meta.get("title")) if title: body["title"] = title elif not artifact_id: die("A new artifact needs a title: --title TEXT (or --artifact ID to publish the next version of one).", EXIT_USAGE) if args.note: body["note"] = args.note if args.org: body["org_id"] = args.org # the share card (a link preview of the public page): the command line, else what the folder's artifact.json kept description = args.description if args.description is not None else ( meta.get("description") if isinstance(meta.get("description"), str) else None) if description is not None: if len(" ".join(description.split())) > 300: die("--description is one line of at most 300 characters.", EXIT_USAGE) body["description"] = description # "" says: no description from now on thumbnail = args.thumbnail if args.thumbnail is not None else ( meta.get("thumbnail") if isinstance(meta.get("thumbnail"), str) else None) if thumbnail: name = thumbnail[len("assets/"):] if thumbnail.startswith("assets/") else thumbnail local = dict(assets).get(name) if not local or _artifact_ext(name) not in ("png", "jpg", "jpeg", "webp", "gif", "avif"): if args.thumbnail is not None: die("The thumbnail is an image in the folder's assets/ (.png .jpg .jpeg .webp .gif .avif); %s is not one " "of them." % thumbnail, EXIT_USAGE) # remembered in artifact.json and gone from assets/ since: the page is published without one, and says so print("lhbox: artifact.json names the thumbnail %s, which is not in assets/ any more: published without " "one (--thumbnail FILE names another)." % thumbnail, file=sys.stderr) thumbnail = None if thumbnail: # stored by content: the name the API keeps it under is known before it is sent body["thumbnail"] = "assets/%s.%s" % (hashlib.sha256(_artifact_bytes(local)).hexdigest(), _artifact_ext(name)) thumbnail = name meta_dir = args.page if os.path.isdir(args.page) else None # where artifact.json is written after known_title = title or meta.get("title") or (prev or {}).get("title") if len(pages) == 1 and not assets: body["html"] = _artifact_bytes(pages[0][1]).decode("utf-8", errors="replace") out = request(args, "POST", "/v1/artifacts", body, timeout=SLOW_ADMIN_TIMEOUT) return _artifact_published(args, out, 1, meta_dir, catalogs, known_title, description, thumbnail) started = request(args, "POST", "/v1/artifacts", body) aid, version = started["artifact_id"], started["version"] base = "/v1/artifacts/%s/versions/%s" % (urllib.parse.quote(aid, safe=""), version) stored = {} # an asset's local name -> the name it is stored under (assets/.) for name, full in assets: got = request(args, "PUT", base + "/files/" + urllib.parse.quote(name, safe=""), raw_body=_artifact_bytes(full), content_type="application/octet-stream", timeout=SLOW_ADMIN_TIMEOUT) stored[name] = str(got.get("path") or "").split("/", 1)[-1] for rel, full in pages: data = _artifact_bytes(full) for name, kept in stored.items(): # `assets/logo.png` in a page file becomes the stored `assets/.png` if kept and kept != name: data = data.replace(("assets/" + name).encode(), ("assets/" + kept).encode()) folder, _, name = rel.rpartition("/") request(args, "PUT", base + "/files/" + urllib.parse.quote(name, safe="") + ("?dir=" + urllib.parse.quote(folder, safe="") if folder else ""), raw_body=data, content_type=ARTIFACT_CONTENT_TYPES.get(_artifact_ext(name), "application/octet-stream"), timeout=SLOW_ADMIN_TIMEOUT) out = request(args, "POST", base + "/publish", timeout=SLOW_ADMIN_TIMEOUT) _artifact_published(args, out, len(pages) + len(assets), meta_dir, catalogs, known_title, description, thumbnail) def _artifact_write_meta(folder, out, catalogs, title, note, description=None, thumbnail=None): """A published folder gets the artifact.json `pull` writes (#3128): the next `lhbox artifact publish ` publishes the next version of THIS artifact, with its catalogs, instead of a second artifact. -> its path, or None when the folder cannot be written (the publish itself is done either way).""" meta_file = os.path.join(folder, ARTIFACT_META) meta = {} try: with open(meta_file, encoding="utf-8") as fh: meta = json.load(fh) except (OSError, ValueError): pass if not isinstance(meta, dict): meta = {} meta.update({k: v for k, v in (("artifact_id", out.get("artifact_id")), ("title", title), ("version", out.get("version")), ("catalogs", catalogs), ("note", note), ("url", out.get("url")), ("description", description), ("thumbnail", thumbnail)) if v is not None}) try: tmp = os.path.join(folder, "." + ARTIFACT_META + ".tmp") # a dot file: never taken for a page file with open(tmp, "w", encoding="utf-8") as fh: fh.write(json.dumps(meta, indent=2, ensure_ascii=False) + "\n") os.replace(tmp, meta_file) except OSError: return None return meta_file def _artifact_published(args, out, files, folder=None, catalogs=None, title=None, description=None, thumbnail=None): out = dict(out, files=files) if folder and out.get("artifact_id"): out["artifact_json"] = _artifact_write_meta(folder, out, catalogs, title, getattr(args, "note", None), description, thumbnail) if _want_json(args): print_json(out) return print("Published %s, version %s (%d file%s)." % (out.get("artifact_id"), out.get("version"), files, "" if files == 1 else "s")) print("It is private to its owner until they share it: %s" % out.get("url")) # the API's warnings about the page (never a refusal): what to fix in the next version, and where it is explained warnings = [w for w in out.get("warnings") or [] if isinstance(w, dict)] if warnings: print("%d thing%s to fix in the next version:" % (len(warnings), "" if len(warnings) == 1 else "s"), file=sys.stderr) for w in warnings: print(" - %s %s" % (w.get("message") or w.get("code"), w.get("remedy") or ""), file=sys.stderr) if w.get("docs"): print(" %s" % w["docs"], file=sys.stderr) def _download(args, path, timeout=SLOW_ADMIN_TIMEOUT): """One authenticated GET whose answer is a file -> (bytes, content type). An HTTP error ends as every request's does (the API's envelope, _fail); the network's failures as request_status's.""" url = args.url.rstrip("/") + path req = urllib.request.Request(url, method="GET") req.add_unredirected_header("Authorization", "Bearer " + _bearer(args)) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.read(), (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower() except (TimeoutError, socket.timeout): _die_timeout("GET", path.split("?")[0], timeout) except urllib.error.HTTPError as e: raw = e.read() try: parsed = json.loads(raw) except Exception: parsed = {"error": {"code": "http_%d" % e.code, "message": raw.decode(errors="replace")[:500]}} _fail("GET", path, e.code, parsed) except urllib.error.URLError as e: if _is_timeout(e): _die_timeout("GET", path.split("?")[0], timeout, sent=False) _die_unreachable("GET", url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url("GET", path, e) def _artifact_slug(title): import unicodedata plain = unicodedata.normalize("NFKD", str(title or "")).encode("ascii", "ignore").decode().lower() return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")[:60].strip("-") or "artifact" def cmd_artifact_pull(args): """The current version's files into a folder: page/ (index.html and the page's other files), assets/ (under the names they are stored by, which is how the page refers to them: ../assets/.) and artifact.json (its id, title, catalogs, version and note), which `lhbox artifact publish ` reads to publish the next version.""" import io import zipfile ref = urllib.parse.quote(args.artifact, safe="") art = request(args, "GET", "/v1/artifacts/" + ref) dest = args.dir or _artifact_slug(art.get("title")) if os.path.exists(dest) and (not os.path.isdir(dest) or os.listdir(dest)) and not args.force: die("%s exists and is not empty; name another folder, or --force to write into it." % _shown_path(dest), EXIT_ERROR) data, ctype = _download(args, "/v1/artifacts/" + ref + "/export") files = {} if ctype == "application/zip" or data[:2] == b"PK": try: with zipfile.ZipFile(io.BytesIO(data)) as z: for name in z.namelist(): parts = name.split("/") # only what an export holds, at a path inside the folder: v/ and assets/ if name.endswith("/") or ".." in parts or name.startswith(("/", "\\")) or "\\" in name: continue if re.match(r"^v[0-9]+$", parts[0]) and len(parts) > 1: if parts[1:] != ["manifest.json"]: files["page/" + "/".join(parts[1:])] = z.read(name) elif parts[0] == "assets" and len(parts) == 2 and ARTIFACT_STORED_ASSET.match(parts[1]): files[name] = z.read(name) except zipfile.BadZipFile: die("The export did not answer a readable archive; nothing was written.", EXIT_SERVER) else: files["page/index.html"] = data if "page/index.html" not in files: die("The export holds no index.html; nothing was written.", EXIT_SERVER) meta = {"artifact_id": art.get("artifact_id"), "title": art.get("title"), "version": art.get("current_version"), "catalogs": art.get("catalogs") or [], "note": art.get("note"), "url": art.get("url")} # the share card, so the next publish of the folder keeps it: the thumbnail by the name pull writes it under in assets/ if art.get("description"): meta["description"] = art["description"] if isinstance(art.get("thumbnail"), str) and art["thumbnail"].startswith("assets/"): meta["thumbnail"] = art["thumbnail"][len("assets/"):] files[ARTIFACT_META] = (json.dumps(meta, indent=2, ensure_ascii=False) + "\n").encode() for rel, content in files.items(): full = os.path.join(dest, *rel.split("/")) os.makedirs(os.path.dirname(full) or ".", exist_ok=True) with open(full, "wb") as fh: fh.write(content) out = {"artifact_id": art.get("artifact_id"), "version": art.get("current_version"), "dir": dest, "files": sorted(files)} if _want_json(args): print_json(out) return print("Wrote version %s of %s into %s (%d files)." % (out["version"], out["artifact_id"], _shown_path(dest), len(files))) print("Change page/index.html, then: lhbox artifact publish %s --note \"what changed\"" % _shown_path(dest)) def cmd_artifact_ls(args): out = request(args, "GET", "/v1/artifacts" + ("?deleted=true" if args.deleted else "")) arts = [a for a in out.get("artifacts") or [] if not args.org or a.get("org_id") == args.org] if _want_json(args): print_json({"artifacts": arts}) return rows = [{"artifact_id": a.get("artifact_id"), "title": a.get("title"), "version": "" if a.get("limited") else a.get("current_version"), "updated": str(a.get("updated_at") or "")[:16], "access": "someone else's" if a.get("limited") else {"org": "organisation", "public": "public"}.get(a.get("sharing"), "private"), "agent": (a.get("agent") or {}).get("name") or "", "note": a.get("note") or "", "restorable_until": str(a.get("purge_after") or "")[:10]} for a in arts] if args.deleted: # the trash: when each is purged, and how to get one back emit(args, rows, ["artifact_id", "title", "access", "restorable_until"]) if rows: print("Restore one: lhbox artifact restore ID") return emit(args, rows, ["artifact_id", "title", "version", "updated", "access", "agent", "note"]) def cmd_artifact_delete(args): """DELETE /v1/artifacts/{id}: into the trash (restorable for 30 days, the same id and address). A person deletes their own (an admin, any of the organisation's); an agent's key what it may publish to. Asked on a terminal unless --yes; without a terminal it goes ahead (it can be undone), with a note on stderr unless the output is JSON.""" ref = urllib.parse.quote(args.artifact, safe="") if not (getattr(args, "yes", False) or getattr(args, "confirm", None)): if sys.stdin.isatty() and sys.stdout.isatty() and not args.json: if _ask("Delete artifact %s? Nobody opens it from now; it can be restored for 30 days. [y/N] " % args.artifact).strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was changed.", EXIT_USAGE) elif not _want_json(args): print("note: deleting without --yes (no terminal to ask on).", file=sys.stderr) out = request(args, "DELETE", "/v1/artifacts/" + ref) if _want_json(args): print_json(out) return sid = out.get("artifact_id") or args.artifact print("%s %s \"%s\"." % ("Already deleted:" if out.get("already_deleted") else "Deleted", sid, out.get("title") or "")) if out.get("message"): print(out["message"]) if out.get("owner_notified"): print("Its owner was told by mail, with the way to restore it.") print("Restore it until %s: lhbox artifact restore %s" % (str(out.get("purge_after") or "")[:10], sid)) def cmd_artifact_check(args): """GET /v1/artifacts/{id}/check: the current version checked without running it. Exit 0 when `ok`, 1 when it has a problem (a file its page refers to and does not hold, a catalog nobody reads through it): a CI step can gate on it. Warnings never change the exit code. A file or folder on disk is checked here instead, before it is published: what a publish of it would stop at (_artifact_layout), with no request.""" # an id is 8 letters and digits (or the older a_ + 22): a folder `pull` named like one is read as the id unless # written as a path (./Ab12Cd34) looks_like_id = re.fullmatch(r"[A-Za-z0-9]{8}|a_[A-Za-z0-9_-]{22}", args.artifact) is not None if os.path.exists(args.artifact): if not looks_like_id or os.sep in args.artifact or "/" in args.artifact: return _artifact_check_local(args) if not _want_json(args): print("lhbox: checking the artifact %s; to check the folder of that name before publishing it: lhbox " "artifact check ./%s" % (args.artifact, args.artifact), file=sys.stderr) out = request(args, "GET", "/v1/artifacts/%s/check" % urllib.parse.quote(args.artifact, safe="")) problems = [p for p in out.get("problems") or [] if isinstance(p, dict)] warnings = [w for w in out.get("warnings") or [] if isinstance(w, dict)] if _want_json(args): print_json(out) else: print("Artifact %s, version %s: %s, %s of %s, %s of %s files." % ( out.get("artifact_id") or args.artifact, out.get("version"), "ok" if out.get("ok") else "%d problem%s" % (len(problems), "" if len(problems) == 1 else "s"), fmt_bytes(out.get("bytes")), fmt_bytes(out.get("limit_bytes")), out.get("files"), out.get("limit_files"))) for label, items in (("Problems", problems), ("Warnings", warnings)): if items: print("%s:" % label) for p in items: print(" - %s %s" % (_visible(p.get("message") or p.get("code")), _visible(p.get("remedy") or ""))) if p.get("docs"): print(" %s" % _visible(p["docs"])) cats = [c for c in out.get("catalogs") or [] if isinstance(c, dict)] if cats: print("Catalogs: %s" % ", ".join("%s (%s)" % (_visible(c.get("name")), "read" if c.get("readable") else _visible(c.get("reason"))) for c in cats)) if out.get("not_checked"): print("Not read (past what one check reads): %s" % ", ".join(_visible(p) for p in out["not_checked"])) if out.get("note"): print(out["note"]) if not out.get("ok", True): sys.exit(EXIT_ERROR) def _artifact_check_local(args): """`lhbox artifact check DIR`: the folder's layout as `publish` reads it -> {path, ok, problems, pages, assets, note}; exit 1 when the publish would stop (a file type or a place an artifact does not take).""" pages, assets, _, problem = _artifact_layout(args.artifact) out = {"path": args.artifact, "ok": problem is None, "problems": [problem] if problem else [], "pages": len(pages), "assets": len(assets), "note": "The folder as a publish reads it; nothing was sent. Once published, `lhbox artifact check ID` also " "reads every page file for missing files and for addresses the page's frame blocks."} if _want_json(args): print_json(out) else: if problem is None: print("%s: ok, %d page file%s, %d asset%s." % (_shown_path(args.artifact), len(pages), "" if len(pages) == 1 else "s", len(assets), "" if len(assets) == 1 else "s")) else: print("%s: a publish of it would stop here." % _shown_path(args.artifact)) print("Problems:") print(" - %s" % problem["message"]) print(out["note"]) if problem: sys.exit(EXIT_ERROR) def cmd_artifact_restore(args): """POST /v1/artifacts/{id}/restore: back from the trash, with the same id and address, private.""" out = request(args, "POST", "/v1/artifacts/%s/restore" % urllib.parse.quote(args.artifact, safe="")) if _want_json(args): print_json(out) return print("Restored %s \"%s\" at %s." % (out.get("artifact_id") or args.artifact, out.get("title") or "", out.get("url") or "")) if out.get("sharing_before") and out.get("sharing_before") != "private": print("It was %s; it comes back private: share it again from the page." % {"org": "shared with the organisation", "public": "public"}.get(out["sharing_before"], out["sharing_before"])) def cmd_agent_models(args): out = request(args, "GET", "/v1/agents/models") if _want_json(args): print_json(out) return rows = [{"model": m.get("model"), "name": m.get("label"), "where": m.get("operator") or m.get("region"), "sees images": "yes" if m.get("vision") else "no", "default": "yes" if m.get("default") else "", "allowance": ("x%s" % m["allowance_multiplier"]) if m.get("allowance_multiplier") is not None else "", "eur/M in": (m.get("eur_per_million_tokens") or {}).get("input"), "eur/M out": (m.get("eur_per_million_tokens") or {}).get("output")} for m in out.get("models") or []] emit(args, rows, ["model", "name", "where", "sees images", "default", "allowance", "eur/M in", "eur/M out"]) if not _want_json(args) and out.get("allowance_unit"): print("\nThe allowance counts %s; a model marked x2 uses it about twice as fast (at a typical run's mix of input " "and output; a model that writes long answers uses it faster). Choose one with: lhbox agent update " "--model " % out["allowance_unit"]) def cmd_agent_show(args): out = request(args, "GET", _agent_path(args)) if _want_json(args): print_json(out) return _print_agent(out) def cmd_agent_update(args): pairs = (("--no-catalogs and --catalog", args.no_catalogs and args.catalog), ("--no-state-keys and --state-key", args.no_state_keys and args.state_key), ("--no-topics and --topic", args.no_topics and args.topic), ("--no-schedule and --schedule", args.no_schedule and args.schedule), ("--no-integrations and --integration", args.no_integrations and args.integration), ("--no-writes and --write", args.no_writes and args.write), ("--no-on-commit and --on-commit", args.no_on_commit and args.on_commit), ("--no-on-commit-if and --on-commit-if", args.no_on_commit_if and args.on_commit_if is not None), ("--no-web and --allow-host/--host-credential", args.no_web and (args.allow_host or args.host_credential))) if any(both for _, both in pairs): pair = next(p for p, both in pairs if both) die("%s contradict each other." % pair, EXIT_USAGE) body = _agent_body(args, creating=False) if args.pause or args.resume: body["paused"] = bool(args.pause) if getattr(args, "confirm_definition", False): body["confirm_definition"] = True if getattr(args, "restore_version", None): if set(body) - {"confirm_definition"}: die("--restore-version puts a whole earlier definition back: pass it alone (--confirm-definition at most).", EXIT_USAGE) body["restore_version"] = args.restore_version if not body: die("Nothing to change: pass --prompt, --catalog/--no-catalogs, --state-key/--no-state-keys, --topic/--no-topics, " "--schedule/--no-schedule, " "--integration/--no-integrations, --write/--no-writes, --on-commit/--no-on-commit, " "--on-commit-if/--no-on-commit-if, --allow-host/--host-credential/--no-web, " "--notify-owner/--no-notify-owner, --run-seconds, --max-tool-calls, " "--model, --confirm-definition, --pause or --resume.", EXIT_USAGE) for attempt in range(AGENT_UPDATE_TRIES): if "if_version" not in body or attempt + 1 == AGENT_UPDATE_TRIES: out = request(args, "PATCH", _agent_path(args), body) break try: with _quiet(): out = request(args, "PATCH", _agent_path(args), body) break except _Fatal: raise except _Refused as r: err = (r.parsed or {}).get("error") or {} if isinstance(r.parsed, dict) else {} if r.status == 400 and "if_version" in (err.get("unknown") or []): body.pop("if_version") # a control plane from before #2722: the change as before it continue if r.status != 409 or err.get("code") != "version_conflict": _fail("PATCH", _agent_path(args), r.status, r.parsed) # #2722: another change was saved after this one read the agent's hosts and keys: add to what it holds now body["web"] = _web_body(args, keep_current=True) body["if_version"] = args._agent_read_version _print_integration_review(out) if _want_json(args): print_json(out) return _print_agent(out) AGENT_UPDATE_TRIES = 3 # --host-credential alone re-reads the agent and adds again after a version_conflict def cmd_agent_subscribe(args): out = request(args, "POST", _agent_path(args, "/subscribers/me"), {}) if _want_json(args): print_json(out) return print("You will get %s's notices by email (each has a link to stop them; lhbox agent unsubscribe %s)." % ( args.name, args.name)) def cmd_agent_unsubscribe(args): out = request(args, "DELETE", _agent_path(args, "/subscribers/me")) if _want_json(args): print_json(out) return print("You no longer get %s's notices." % args.name) def cmd_agent_delete(args): _confirm_irreversible(args, "Delete agent %s (its identity is suspended; its runs stay readable)" % args.name) emit(args, request(args, "DELETE", _agent_path(args))) def _print_agent_run(r): u = r.get("usage") or {} print("%s %s: %s%s." % ("Test run" if r.get("dry_run") else "Run", str(r.get("run_id", ""))[:8], r.get("state"), (", %s tokens" % r["tokens_charged"]) if r.get("tokens_charged") is not None else "")) if u.get("requests") is not None: print(" model requests: %s, tool calls: %s" % (u.get("requests"), u.get("tool_calls"))) err = r.get("error") or {} if err: print(" error: %s%s" % (err.get("code"), (" -- " + err["message"]) if err.get("message") else "")) _print_run_record(r) if r.get("output"): print() print(r["output"]) def _print_run_record(r): """What the run did (GET /v1/agent-runs/{id}, or runs --detail): its tool calls, notices, memory before and after.""" trace = r.get("trace") if isinstance(trace, dict) and (trace.get("calls") or trace.get("elided")): print(" tool calls:") if trace.get("elided"): print(" (%s earlier calls not kept)" % trace["elided"]) for i, c in enumerate(trace.get("calls") or [], 1): args = c.get("arguments") or {} what = args.get("sql") if isinstance(args, dict) and "sql" in args else json.dumps(args, ensure_ascii=False) what = str(what).replace("\n", " ") print(" %2d. %s %s -> %s%s%s" % (i, c.get("tool"), what[:120] + ("..." if len(what) > 120 else ""), c.get("outcome"), (": " + str(c["summary"])) if c.get("summary") else "", (" (%s ms)" % c["ms"]) if c.get("ms") is not None else "")) for n in r.get("notices") or []: print(" email sent to %s: %s" % (n.get("sent_to"), n.get("subject"))) if n.get("body"): for line in str(n["body"]).splitlines()[:12]: print(" | " + line) before, after = r.get("state_before"), r.get("state_after") if isinstance(after, dict) and after != before: label = "memory it would write (test run, not written)" if r.get("dry_run") else "memory written" print(" %s:" % label) for k in sorted(after): if (before or {}).get(k) != after[k]: print(" %-14s %s" % (k + ":", str(after[k])[:160].replace("\n", " "))) _POLL_NOTE = {"next": 0.0, "last": None} def _poll_gave_up(args, path, remedy, **detail): """The wait ran out while its last poll failed (_poll_get): that failure as the one envelope, exit 5, with what the wait was about (detail) and what to do (remedy) -- never `safe to retry` alone, which for `agent run` starts another.""" status, body = _POLL_NOTE["last"] if not status: # the transport failure the last poll met (unreachable, timeout, connection_lost), as it would have been said err = dict((body.get("error") or {}) if isinstance(body, dict) else {}) err.update(detail, remedy=remedy) die_json(err.pop("code", "unreachable"), err.pop("message", "The API did not answer GET %s." % path), EXIT_SERVER, **err) err = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), dict) else None if err is None: body = {"error": {"code": "http_%d" % status, "message": "GET %s answered HTTP %d" % (path, status)}} err = body["error"] err.update(detail, remedy=remedy) _fail("GET", path, status, body) def _poll_get(args, path, deadline): """One GET of a --wait loop, through what a wait should outlive (#2638): an unreachable API, a timeout, a lost answer, 429 and 5xx -> None, and the caller polls again until its deadline, then reports the last state it read (exit 5) with the run or integration named, or that last failure (_poll_gave_up); a line on stderr at most once a minute meanwhile. A 429 waits its retry_after_seconds. A refusal (4xx) is the command's answer (_fail).""" _SILENT.on = True try: status, body = request_status(args, "GET", path) except SystemExit as e: if e.code != EXIT_SERVER: raise status, body = 0, getattr(_SILENT, "envelope", None) or {} finally: _SILENT.on = False _SILENT.envelope = None _POLL_NOTE["last"] = None if status == 0 or status == 429 or status >= 500: _POLL_NOTE["last"] = (status, body) if time.time() >= _POLL_NOTE["next"] and time.time() < deadline: print("cannot read %s right now (%s); still waiting, %d min left" % (path, "HTTP %d" % status if status else "no answer", _minutes_left(deadline)), file=sys.stderr, flush=True) _POLL_NOTE["next"] = time.time() + 60 if status == 429: err = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), dict) else {} time.sleep(max(0, min(int(err.get("retry_after_seconds") or 0) - 3, deadline - time.time()))) return None if status >= 400: _fail("GET", path, status, body) return body def cmd_agent_run(args): run = request(args, "POST", _agent_path(args, "/run"), {"dry_run": True} if args.dry_run else {}) if not args.wait: if _want_json(args): print_json(run) else: print("%s %s queued (%s tokens held); follow it with: lhbox agent runs %s --detail" % ( "Test run" if run.get("dry_run") else "Run", run["run_id"][:8], run.get("hold_tokens"), args.name)) return deadline = time.time() + args.timeout cur = run while time.time() < deadline: # a busy or failing poll is not the run's end (#2638): it ended the wait with exit 5, the retry code, and a script # that retried started (and paid for) a second run while the first went on got = _poll_get(args, "/v1/agent-runs/%s" % urllib.parse.quote(run["run_id"]), deadline) if got is not None: cur = dict(got, run_id=got.get("run_id") or run["run_id"]) if cur.get("state") in AGENT_RUN_DONE: break time.sleep(3) if cur.get("state") not in AGENT_RUN_DONE and _POLL_NOTE["last"]: _poll_gave_up(args, "/v1/agent-runs/%s" % urllib.parse.quote(run["run_id"]), "The run goes on: follow it with `lhbox agent runs %s` (run %s). Running the command again starts " "and pays for another run." % (args.name, run["run_id"]), run_id=run["run_id"]) if _want_json(args): print_json(cur) else: _print_agent_run(cur) if cur.get("state") not in AGENT_RUN_DONE: print(" still %s after %s s; follow it with: lhbox agent runs %s" % (cur.get("state"), args.timeout, args.name)) if cur.get("state") not in AGENT_RUN_DONE: sys.exit(EXIT_SERVER) # still queued/running when --timeout ran out: not a result (review of the CLI PR) if cur.get("state") != "succeeded": sys.exit(EXIT_ERROR) def cmd_agent_brief(args): out = request(args, "GET", _agent_path(args, "/brief")) if _want_json(args): print_json(out) return print("Agent %s%s, next run %s" % (out.get("agent"), " (PAUSED)" if out.get("paused") else "", out.get("next_run_at") or "none")) att = out.get("attention") or [] print("\nNeeds you:" if att else "\nNothing needs you.") for x in att: extra = x.get("since") or x.get("check_after") or x.get("at") or "" print(" - %s: %s%s" % (x.get("what"), x.get("detail") or "", (" (%s)" % extra) if extra else "")) mem = out.get("memory") if mem: print("\nWhat the agent sees (its memory view):\n" + (mem.get("text") or "")) elif out.get("withheld"): print("\nIts memory is shown to a person only (it used a person's integrations): use your own key.") elif out.get("state"): print("\nRemembered: %s" % json.dumps(out["state"], ensure_ascii=False)) rows = [{"run": str(r.get("run_id", ""))[:8], "trigger": r.get("trigger"), "state": r.get("state"), "finished": r.get("finished_at"), "error": r.get("error")} for r in out.get("runs") or []] if rows: print() emit(args, rows, ["run", "trigger", "state", "finished", "error"]) def _print_talk(args, t): """One exchange: what was said, the agent's reply, and what it proposes (the prompt as a unified diff).""" import difflib print("You: %s" % t.get("message")) if t.get("reply"): print("%s: %s" % (args.name, t["reply"])) p = t.get("proposal") or {} if p.get("prompt"): print("\nIts prompt would become (nothing changes until you apply):") for line in difflib.unified_diff((p["prompt"].get("before") or "").splitlines(), (p["prompt"].get("after") or "").splitlines(), "before", "after", lineterm="", n=2): print(" " + line) for r in p.get("resolve") or []: print("It would mark done: [%s/%s] %s -> %s" % (r.get("topic"), r.get("item"), r.get("what") or "", r.get("outcome"))) acted = t.get("acted") or {} if acted.get("applied"): print("\nApplied what it proposed%s%s." % (" (version %s)" % acted["version"] if acted.get("version") else "", ", marked done: " + ", ".join(acted["resolved"]) if acted.get("resolved") else "")) elif acted.get("discarded"): print("\nDropped what it proposed; nothing changed.") elif acted.get("not_applied"): print("\nWhat it proposed could not be applied (%s): ask again." % acted.get("code")) if t.get("state") == "proposed": print('\nTo apply it, say so: lhbox agent talk %s "yes"' % args.name) elif t.get("state") not in (None, "answered"): print("(%s)" % t["state"]) def cmd_agent_talk(args): """lhbox agent talk NAME "message" [--about TOPIC/ITEM] | (nothing: the latest exchanges). A yes to what it proposed is a message too ("yes"): there is no separate apply.""" if not args.message: out = request(args, "GET", _agent_path(args, "/talk?limit=%d" % args.limit)) if _want_json(args): print_json(out) return talks = out.get("talks") or [] if not talks: print("Nothing said to %s yet." % args.name) for t in reversed(talks): print("=" * 20, t.get("created_at")) _print_talk(args, t) return body = {"message": args.message} if args.about: topic, sep, item = args.about.partition("/") if not (sep and topic and item): die("--about is TOPIC/ITEM, as the brief shows it ([lawn/hold-watering]).", EXIT_USAGE) body["about"] = {"topic": topic, "item": item} out = request(args, "POST", _agent_path(args, "/talk"), body, timeout=180) # the agent may think up to ~2 min if _want_json(args): print_json(out) return _print_talk(args, out) def cmd_agent_runs(args): out = request(args, "GET", _agent_path(args, "/runs?limit=%d%s" % (args.limit, "&detail=true" if args.detail else ""))) if _want_json(args): print_json(out) return if args.detail: for r in out.get("runs") or []: print("%s (%s, %s)" % ("=" * 20, r.get("created_at"), r.get("trigger") + (", test run" if r.get("dry_run") else ""))) _print_agent_run(r) return rows = [{"run": str(r.get("run_id", ""))[:8], "trigger": "test" if r.get("dry_run") else r.get("trigger"), "state": r.get("state"), "tokens": r.get("tokens_charged"), "requests": (r.get("usage") or {}).get("requests"), "created": r.get("created_at"), "error": (r.get("error") or {}).get("code")} for r in out.get("runs") or []] emit(args, rows, ["run", "trigger", "state", "tokens", "requests", "created", "error"]) # ------------------------------------------------------------------ integrations (research/47 milestone 3) INTEGRATION_MCP = {"github": "https://api.githubcopilot.com/mcp/"} # a shorthand; --mcp names any MCP server def _integration_path(ref, tail=""): return "/v1/integrations/%s%s" % (urllib.parse.quote(ref), tail) def _print_integration(i): print("Integration %s: %s" % (i.get("name"), i.get("state"))) if i.get("kind") == "web": # a web key (fetch_url): a host, not an MCP server where = i.get("key_in") or {} print(" web key for: %s" % i.get("web_host")) print(" sent as: %s" % ("query parameter %s" % where["query"] if where.get("query") else "header %s" % where.get("header"))) print(" key: %s" % (i.get("api_key_hint") or "stored")) return print(" service: %s (%s)" % (i.get("service") or "?", i.get("provider") or "?")) print(" server: %s" % i.get("server_url")) print(" sign-in: %s" % {"oauth": "OAuth", "api_key": "API key %s" % (i.get("api_key_hint") or ""), "none": "none needed"}.get(i.get("auth") or "oauth", i.get("auth"))) details = i.get("tool_details") or [{"name": t} for t in i.get("tools") or []] if not details: print(" tools: none") for n, t in enumerate(details): ann = t.get("annotations") or {} hint = " (read-only)" if ann.get("readOnlyHint") else " (destructive)" if ann.get("destructiveHint") else "" print(" %s %s%s" % ("tools: " if n == 0 else " ", t.get("name"), hint)) print(" scopes: %s" % (", ".join(i.get("scopes") or []) or "none")) if i.get("connected_at"): print(" connected: %s" % i["connected_at"]) if i.get("last_error"): print(" last error: %s" % i["last_error"]) if i.get("repositories_url"): # a GitHub App: agents reach the repositories it is installed on; choose or change them there, no reconnect print(" repositories: %s" % i["repositories_url"]) def _wait_command(out): # by id (#2721): a name held in two of the caller's organisations answers 409 integration_ambiguous return "lhbox integration wait %s --previous %s" % (out.get("integration_id") or out.get("name"), out.get("connected_at") or "-") def _consent(args, out): """Print the link to open, open it only when asked (--open), and with --wait poll until the person consented. A JSON caller gets one document: the answer with the link and `wait_command` (--json --wait is refused: nothing could show the link before the wait ends, review of part B).""" link = out.get("authorize_url") if _want_json(args): if args.open and link: _open_browser(link) print_json(dict(out, wait_command=_wait_command(out))) return if not link: # an API key or a server that needs none: connected already _print_integration(out) return where = "a browser where you are signed in to LakehouseBox" if out.get("open_in") else "your own browser" print("Open this link in %s and approve (it works once, for %d minutes):" % (where, (out.get("authorize_expires_in") or 600) // 60)) print(" %s" % link) if args.open and link: _open_browser(link) if not args.wait: print("Then: %s" % _wait_command(out)) return _wait_consent(args, out["integration_id"], out.get("connected_at"), out.get("state")) def _wait_consent(args, ref, previous, state_before): """Done when the integration was connected again (connected_at changed from `previous`: a reconnect keeps the state it had, review of part B) or it failed; exit 0, 1, or 5 when --timeout ran out.""" deadline = time.time() + args.timeout cur = None while True: # a busy poll waits on (#2638); with no answer at all yet, the integration is named and its state unknown cur = _poll_get(args, _integration_path(ref), deadline) or cur or {"integration": ref, "state": None} connected = cur.get("state") == "active" and cur.get("connected_at") and cur.get("connected_at") != previous failed = cur.get("state") == "failed" and state_before != "failed" if connected or failed or time.time() >= deadline: break time.sleep(3) if not (connected or failed) and _POLL_NOTE["last"]: _poll_gave_up(args, _integration_path(ref), "Check it with `lhbox integration list`; `lhbox integration wait %s` " "waits again." % ref, integration=ref) if _want_json(args): print_json(cur) else: _print_integration(cur) if not (connected or failed): sys.exit(EXIT_SERVER) # nobody consented within --timeout: not a result if failed: sys.exit(EXIT_ERROR) def cmd_integration_wait(args): previous = None if args.previous in (None, "", "-") else args.previous _wait_consent(args, args.ref, previous, None) def _no_json_wait(args): if args.wait and _want_json(args): die("--wait with --json has nowhere to show the link before it ends: run it without --wait (the answer holds " "authorize_url and wait_command), give the person the link, then run wait_command.", EXIT_USAGE) def cmd_integration_add(args): _no_json_wait(args) if args.web_key: return _integration_add_web_key(args) if args.host or args.key_param: die("--host and --key-param go with --web-key.", EXIT_USAGE) url = args.mcp or INTEGRATION_MCP.get(args.name) if not url: die("Name the MCP server: --mcp URL (known shorthands: %s)." % ", ".join(sorted(INTEGRATION_MCP)), EXIT_USAGE) body = {"name": args.name, "mcp_url": url} if args.org: body["org_id"] = args.org if args.scope: body["scopes"] = args.scope if args.header and not args.api_key_stdin: die("--header goes with --api-key-stdin.", EXIT_USAGE) if args.api_key_stdin: # the key from stdin, never an argument (it would sit in the history) key = sys.stdin.readline().strip() if not key: die("--api-key-stdin: no key on stdin.", EXIT_USAGE) body.update(auth="api_key", api_key=key) if args.header: body["header_name"] = args.header _consent(args, request(args, "POST", "/v1/integrations", body)) def _integration_add_web_key(args): """A web API's key for an agent's fetch_url: {auth: web_key, host, api_key, header_name | key_param}.""" if args.mcp or args.scope: die("--web-key names a host (--host), not an MCP server.", EXIT_USAGE) if not args.host or not args.api_key_stdin: die("--web-key needs --host HOST and --api-key-stdin (the key is read from stdin, never an argument).", EXIT_USAGE) if args.header and args.key_param: die("The key goes in a header (--header) or a query parameter (--key-param), not both.", EXIT_USAGE) key = sys.stdin.readline().strip() if not key: die("--api-key-stdin: no key on stdin.", EXIT_USAGE) body = {"name": args.name, "auth": "web_key", "host": args.host, "api_key": key} if args.header: body["header_name"] = args.header if args.key_param: body["key_param"] = args.key_param if args.org: body["org_id"] = args.org out = request(args, "POST", "/v1/integrations", body) if _want_json(args): print_json(out) return _print_integration(out) print("Give it to an agent: lhbox agent update AGENT --allow-host %s --host-credential %s=%s" % ( out.get("web_host"), out.get("web_host"), out.get("name"))) def cmd_integration_reconnect(args): _no_json_wait(args) _consent(args, request(args, "POST", _integration_path(args.ref, "/reconnect"), {})) def cmd_integration_list(args): out = request(args, "GET", "/v1/integrations" + (("?org_id=" + urllib.parse.quote(args.org)) if args.org else "")) if _want_json(args): print_json(out) return rows = [{"name": i.get("name"), "state": i.get("state"), "service": i.get("service"), "tools": len(i.get("tools") or []), "connected": i.get("connected_at"), "id": str(i.get("integration_id", ""))[:8]} for i in out.get("integrations") or []] emit(args, rows, ["name", "state", "service", "tools", "connected", "id"]) def cmd_integration_show(args): out = request(args, "GET", _integration_path(args.ref)) if _want_json(args): print_json(out) return _print_integration(out) def cmd_integration_delete(args): _confirm_irreversible(args, "Delete integration %s (its tokens are revoked at the provider and wiped; agents using " "it stop reaching it)" % args.ref) emit(args, request(args, "DELETE", _integration_path(args.ref))) # ------------------------------------------------------------------ scheduled SQL sinks (research/46) SQL_RUN_DONE = ("materialised", "empty", "failed", "skipped") def _at_file(value, flag): """The text of an @file argument; a file that cannot be read is the caller's mistake (exit 6), never the backstop's unexpected_cli_error (#2429; the shape of docs_file_unreadable, #2023).""" path = value[1:] try: with open(os.path.expanduser(path)) as fh: return fh.read() except OSError as exc: die_json("%s_file_unreadable" % flag.lstrip("-").replace("-", "_"), "Cannot read %s @%s: %s" % (flag, path, exc.strerror or exc), EXIT_USAGE, path=path, remedy="Point %s at a readable file (@path), or give the value inline." % flag) def _file_arg(path, flag, binary=False, json_object=False, remedy=None): """The bytes (binary), the JSON object (json_object) or the text of a file argument. One that cannot be read, or is not the JSON object it should be, is the caller's mistake (exit 6), never main()'s unexpected_cli_error (#2949).""" name = flag.lstrip("-").replace("-", "_") code = name if name.endswith("file") else name + "_file" # send_key_file, mapping_file, file try: with open(os.path.expanduser(path), "rb" if binary else "r") as fh: data = fh.read() except OSError as exc: die_json("%s_unreadable" % code, "Cannot read %s %s: %s" % (flag, path, exc.strerror or exc), EXIT_USAGE, path=path, remedy=remedy or "Point %s at a readable file." % flag) if not json_object: return data try: doc = json.loads(data) except ValueError as exc: doc, why = None, "not JSON (%s)" % exc else: why = "not a JSON object" if not isinstance(doc, dict): die_json("%s_not_json" % code, "%s %s is %s." % (flag, path, why), EXIT_USAGE, path=path, remedy=remedy or "Point %s at a JSON object file." % flag) return doc def _sql_text(value, flag="--sql"): """--sql given inline, as @file, or @- for stdin.""" if value is None: return None if value == "@-": return sys.stdin.read() if value.startswith("@"): return _at_file(value, flag) return value def _print_sql_error(err): """A run's or a preview's error as an agent needs it: the code, the message, the column or host, the remedy.""" if not err: return extra = ", ".join("%s=%s" % (k, err[k]) for k in ("column", "expected", "sample", "host", "reason", "limit") if err.get(k) is not None) print(" error: %s: %s%s" % (err.get("code"), err.get("message"), (" (" + extra + ")") if extra else "")) if err.get("remedy"): print(" remedy: %s" % err["remedy"]) def cmd_sink_preview(args): """POST /v1/sql/preview: run the query once, now; nothing is written.""" body = {"warehouse": resolve_catalog(args), "sql": _sql_text(args.sql)} if args.table: body["table"] = args.table if args.engine: body["engine"] = args.engine if getattr(args, "format_version", None): body["format_version"] = args.format_version out = request(args, "POST", "/v1/sql/preview", body, timeout=180) if _want_json(args): print_json(out) return eg = out.get("egress") or {} # a query that fetched nothing has no egress figures (#1762: it printed "None requests, None bytes from -") fetched = (" (%s request%s, %s bytes from %s)" % (eg.get("requests"), "" if eg.get("requests") == 1 else "s", eg.get("bytes_down") or 0, ", ".join(eg.get("hosts") or []) or "-") if eg.get("requests") else " (no fetches)") print("Preview: %s row%s in %s ms on DuckDB %s%s; nothing written." % ( out.get("row_count"), "" if out.get("row_count") == 1 else "s", out.get("elapsed_ms"), out.get("engine_version") or out.get("engine") or "-", fetched)) cols = out.get("columns") or [] emit(args, [{"column": c["name"], "duckdb": c.get("duckdb_type"), "iceberg": c.get("type") if isinstance(c.get("type"), str) else json.dumps(c.get("type"))} for c in cols], ["column", "duckdb", "iceberg"]) for p in out.get("problems") or []: if p.get("code") == "format_version_conflict": print(" format version %s cannot hold %s (%s): %s" % (p.get("format_version"), p["column"], p.get("type"), p.get("remedy"))) else: print(" no Iceberg type: %s (%s): %s" % (p["column"], p.get("duckdb_type"), p.get("remedy"))) if out.get("create_table_format_version"): print(" create table: format version %s%s" % (out["create_table_format_version"], " (the catalog's default)" if out.get("format_version_source") == "catalog_default" else "")) if "fits_table" in out: if out["fits_table"]: print(" table %s: the rows fit" % out.get("table")) else: print(" table %s: the rows do NOT fit" % out.get("table")) _print_sql_error(out.get("table_error")) rows = out.get("rows") or [] if rows: emit(args, [dict(zip([c["name"] for c in cols], r)) for r in rows[:args.limit]], [c["name"] for c in cols]) # what the preview itself cut (lakehousebox/lakehousebox#5): --limit only chooses how many of its rows to print if out.get("truncated"): if out.get("rows_shown") is not None and out.get("rows_shown") < (out.get("row_count") or 0): print("The preview carries %s of the %s rows (it carries at most %s); the sink's runs keep them all." % ( out["rows_shown"], out.get("row_count"), out.get("max_rows_applied"))) for v in out.get("values_truncated") or []: print("Row %s, column %s: %s characters, cut to %s in the preview; the sink's runs keep the whole value." % ( v.get("row"), v.get("column"), v.get("length"), out.get("max_chars_applied"))) sc = out.get("sink_create") if isinstance(sc, dict) and sc.get("allowed") is False: # an organisation without the feature, or not claimed yet, previews but cannot create the sink (research/72) print("Creating this sink is not possible yet (%s): %s" % (sc.get("code"), sc.get("remedy"))) def cmd_sink_create_sql(args): """POST /v1/sinks with sql: a scheduled SQL sink. No send key exists: nothing to save.""" if not args.every: die("A scheduled SQL sink needs --every (e.g. 20m): how often the query runs.", EXIT_USAGE) body = {"name": args.name, "table": args.table, "warehouse": resolve_catalog(args), "sql": _sql_text(args.sql), "every": args.every} if args.key is not None: body["key"] = _key_arg(args.key) if args.offset: body["offset"] = args.offset if args.create_table: body["create_table"] = True if getattr(args, "partition", None): body["partition"] = list(args.partition) # with --create-table: the API checks it (time only, 400 names it) if getattr(args, "format_version", None): body["format_version"] = args.format_version # with --create-table; without it the catalog's default if args.paused: body["paused"] = True if args.engine: body["engine"] = args.engine if getattr(args, "mode", None): body["mode"] = args.mode if getattr(args, "min_rows", None) is not None: body["min_rows"] = args.min_rows if getattr(args, "replace_existing", False): body["replace_existing"] = True out = request(args, "POST", "/v1/sinks", body, timeout=240) if _want_json(args): print_json(out) return q = out.get("sql") or {} print("SQL sink %s created: every %s s (offset %s s) into table %s of catalog %s%s." % ( out["name"], q.get("every_seconds"), q.get("offset_seconds"), out["table"], out.get("warehouse_name") or _cid(out), " (paused)" if q.get("paused") else "")) if out.get("created_table"): ct = out["created_table"] print(" table: created, format version %s, from the query's columns%s" % ( "%s%s" % (ct.get("format_version"), " (the catalog's default)" if ct.get("format_version_source") == "catalog_default" else ""), (", partitioned by " + ", ".join(ct["partition"])) if ct.get("partition") else "")) if q.get("mode") == "replace": print(" mode: replace: each run replaces every row of the table in one snapshot; a run with fewer than " "%s row(s) fails and leaves the table as it is" % q.get("min_rows")) print(" next run: %s" % (q.get("next_run_at") or "paused")) if out.get("docs_hint"): print(" describe it: %s" % out["docs_hint"]) print("Run it now: lhbox sink run %s --wait" % out["name"]) print("Watch runs: lhbox sink runs %s" % out["name"]) def _run_row(r): err = r.get("error") or {} return {"run": (r.get("run_id") or "")[:8], "trigger": r.get("trigger"), "slot": r.get("slot") or r.get("created_at"), "state": "committed" if r.get("committed") else r.get("state"), "engine": r.get("engine"), "rows": r.get("rows"), "requests": r.get("requests"), "bytes": r.get("bytes_down"), "ms": r.get("elapsed_ms"), "error": ("%s: %s" % (err.get("code"), err.get("message")))[:90] if err else ""} def cmd_sink_runs(args): out = request(args, "GET", "/v1/sinks/%s/runs?limit=%d" % (urllib.parse.quote(args.sink), args.limit)) if _want_json(args): print_json(out) return sched = out.get("schedule") or {} print("Sink %s: every %s s on DuckDB engine %s, %s." % (out.get("name"), sched.get("every_seconds"), sched.get("engine") or "-", ("paused (%s)" % sched.get("paused_reason")) if sched.get("paused") else "next run " + str(sched.get("next_run_at")))) emit(args, [_run_row(r) for r in out.get("runs") or []], ["run", "trigger", "slot", "state", "engine", "rows", "requests", "bytes", "ms", "error"]) def cmd_sink_run(args): run = request(args, "POST", "/v1/sinks/%s/run" % urllib.parse.quote(args.sink), {}) if not args.wait: if _want_json(args): print_json(run) else: print("Run %s queued; follow it with: lhbox sink runs %s" % (run["run_id"][:8], args.sink)) return deadline = time.time() + args.timeout cur = run while time.time() < deadline: runs = request(args, "GET", "/v1/sinks/%s/runs?limit=20" % urllib.parse.quote(args.sink)).get("runs") or [] cur = next((r for r in runs if r["run_id"] == run["run_id"]), cur) if cur.get("state") in SQL_RUN_DONE and (cur.get("state") != "materialised" or cur.get("committed") or time.time() > deadline - 1): break time.sleep(3) if cur.get("state") not in SQL_RUN_DONE: # --timeout ran out: not done, whatever the reason die("Run %s is still %s after %d s: follow it with lhbox sink runs %s" % (cur["run_id"][:8], cur.get("state"), args.timeout, args.sink), EXIT_ERROR) if cur.get("state") == "materialised" and not cur.get("committed"): # stored but never committed within --timeout (#2948): a roller behind, or a sink it disabled -- not "committed" die_json("run_not_committed", "Run %s stored %s rows but nothing committed them within --timeout %d s." % (cur["run_id"][:8], cur.get("rows"), args.timeout), EXIT_ERROR, run_id=cur["run_id"], state="materialised", rows=cur.get("rows"), remedy="lhbox sink get %s shows the sink's state and lag; lhbox sink runs %s shows when the run commits." % (args.sink, args.sink)) if _want_json(args): print_json(cur) else: state = "committed" if cur.get("committed") else cur.get("state") print("Run %s: %s%s." % (cur["run_id"][:8], state, (", %s rows" % cur.get("rows")) if cur.get("rows") is not None else "")) if cur.get("committed"): print(" snapshot: %s" % cur["committed"].get("snapshot_id")) _print_sql_error(cur.get("error")) if cur.get("state") == "failed": sys.exit(EXIT_ERROR) def _patch_sql(args, body, verb): out = request(args, "PATCH", "/v1/sinks/%s" % urllib.parse.quote(args.sink), body, timeout=180) if _want_json(args): print_json(out) return q = out.get("sql") or {} print("Sink %s %s: every %s s (offset %s s) on DuckDB engine %s, %s." % ( out.get("name"), verb, q.get("every_seconds"), q.get("offset_seconds"), q.get("engine") or "-", "paused" if q.get("paused") else "next run " + str(q.get("next_run_at")))) def cmd_sink_pause(args): _patch_sql(args, {"paused": True}, "paused") def cmd_sink_resume(args): _patch_sql(args, {"paused": False}, "resumed") def _key_arg(text): """--key a,b -> ["a", "b"] (research/65: the columns a roll replaces rows on).""" cols = [c.strip() for c in str(text).split(",") if c.strip()] if not cols: die("--key names one or more columns, comma-separated (e.g. --key observation_id); --no-key appends again.", EXIT_USAGE) return cols def cmd_sink_update(args): body = {} if args.sql: body["sql"] = _sql_text(args.sql) if args.every: body["every"] = args.every if args.offset is not None: body["offset"] = args.offset if args.key is not None: body["key"] = _key_arg(args.key) if args.no_key: body["key"] = None if args.engine: body["engine"] = args.engine if getattr(args, "min_rows", None) is not None: body["min_rows"] = args.min_rows if not body: die("Nothing to change: pass --sql, --every, --offset, --engine, --min-rows, --key or --no-key.", EXIT_USAGE) if getattr(args, "force", False): if not {"sql", "engine"} & set(body): die("--force accepts a new --sql or --engine whose preview returns 0 rows; pass one of them.", EXIT_USAGE) body["allow_empty"] = True # a 0-row preview where the recent runs had rows is refused otherwise (#1807) if set(body) == {"key"}: out = request(args, "PATCH", "/v1/sinks/%s" % urllib.parse.quote(args.sink), body, timeout=180) if _want_json(args): print_json(out) return print("Sink %s updated: key %s. %s" % (out.get("name"), ", ".join(out.get("key") or []) or "none (appends)", out.get("key_note") or "")) return _patch_sql(args, body, "updated") def _secret_value(args, what="the credential"): """A connection's value, never from the command line itself (it would be kept in the shell's history and shown by `ps`): --value @FILE or @- (stdin), or --value-env VAR (an agent that holds the key in its environment never writes it anywhere), or, for a person at a terminal with neither, a hidden prompt. One trailing newline is removed.""" value, env = getattr(args, "value", None), getattr(args, "value_env", None) if value and env: die("Give the value one way: --value @FILE, --value @- or --value-env VAR.", EXIT_USAGE) if env: if env not in os.environ: die("The environment variable %s is not set." % env, EXIT_USAGE) text = os.environ[env] elif value: if not value.startswith("@"): die("Give the value as @FILE or @- (stdin), or with --value-env VAR, never inline: a value on the command line " "is kept in the shell's history.", EXIT_USAGE) if value == "@-": text = sys.stdin.read() else: try: with open(os.path.expanduser(value[1:])) as fh: text = fh.read() except OSError as exc: die("Cannot read %s: %s" % (value[1:], exc.strerror), EXIT_USAGE) elif sys.stdin.isatty() and not _want_json(args): import getpass text = getpass.getpass("%s (hidden): " % what[:1].upper() + what[1:], stream=sys.stderr) else: die("Give the value with --value @FILE, --value @- (stdin) or --value-env VAR.", EXIT_USAGE) text = text[:-1] if text.endswith("\n") else text text = text[:-1] if text.endswith("\r") else text if not text: die("The value is empty.", EXIT_USAGE) return text def _query_params(args): """A query connection's {NAME: value} from --param NAME=SOURCE (tablemere#3358), each SOURCE @FILE, @- (stdin, one parameter only) or env:VAR, never a value inline; a bare --param NAME (one parameter) takes --value, --value-env or the hidden prompt, as the other kinds do.""" specs = args.param or [] if len(specs) == 1 and "=" not in specs[0]: return {specs[0]: _secret_value(args, "the value of %s" % specs[0])} if args.value or args.value_env: die("With several --param, give each its own source: --param NAME=@FILE, NAME=@- or NAME=env:VAR.", EXIT_USAGE) out, stdin_used = {}, False for spec in specs: name, sep, src = spec.partition("=") if not sep or not name: die("--param takes NAME=@FILE, NAME=@- or NAME=env:VAR (a bare NAME only when it is the one parameter).", EXIT_USAGE) if name in out: die("--param %s is given twice." % name, EXIT_USAGE) if src.startswith("env:"): ns = argparse.Namespace(**{**vars(args), "value": None, "value_env": src[4:]}) elif src.startswith("@"): if src == "@-": if stdin_used: die("Only one --param can read stdin (@-).", EXIT_USAGE) stdin_used = True ns = argparse.Namespace(**{**vars(args), "value": src, "value_env": None}) else: die("Give --param %s's value as @FILE, @- (stdin) or env:VAR, never inline: a value on the command line " "is kept in the shell's history." % name, EXIT_USAGE) out[name] = _secret_value(ns, "the value of %s" % name) return out def _conn_row(c): header = ",".join(c.get("param_names") or []) if c.get("kind") == "query" else (c.get("header_name") or "") return {"name": c.get("name"), "url_prefix": c.get("url_prefix"), "kind": c.get("kind"), "header": header, "updated": c.get("updated_at")} def cmd_sink_connection_create(args): """POST /v1/sql/connections: a write-only credential for scheduled SQL, bound to one URL prefix.""" kinds = [k for k in ("bearer", "basic") if getattr(args, k)] + (["header"] if args.header else []) \ + (["query"] if args.param else []) if args.kind and args.kind not in kinds: kinds.append(args.kind) if args.integration: # the organisation's web key (#3001 G7): its host, kind and header come from the key; no value is sent if kinds or args.url_prefix or args.value or args.value_env: die("--integration takes the URL prefix, kind and key from the web key: give no --url-prefix, " "--bearer/--header/--basic or --value.", EXIT_USAGE) body = {"warehouse": resolve_catalog(args), "name": args.name, "integration": args.integration} else: if len(kinds) != 1: die("Choose one kind: --bearer, --header NAME, --basic or --param NAME=... (--kind query) (or --integration " "NAME for a web key).", EXIT_USAGE) if kinds[0] == "header" and not args.header: die("--kind header needs --header NAME.", EXIT_USAGE) if kinds[0] == "query" and not args.param: die("--kind query needs at least one --param NAME=@FILE|@-|env:VAR.", EXIT_USAGE) if not args.url_prefix: die("--url-prefix is required (or --integration NAME for a web key).", EXIT_USAGE) body = {"warehouse": resolve_catalog(args), "name": args.name, "url_prefix": args.url_prefix, "kind": kinds[0]} if kinds[0] == "query": body["params"] = _query_params(args) else: body["value"] = _secret_value(args, "user:password" if kinds[0] == "basic" else "the key") if args.header: body["header_name"] = args.header out = request(args, "POST", "/v1/sql/connections", body) if _want_json(args): print_json(out) return named = out.get("header_name") or ", ".join(out.get("param_names") or []) print("Connection %s created in catalog %s: %s%s, sent only to URLs under %s." % ( out["name"], out.get("warehouse_name"), out["kind"], (" (%s)" % named) if named else "", out["url_prefix"])) if out.get("kind") == "query": print("http_get and http_post add the parameter%s to the URL's query string under that prefix; do not set %s " "in the SQL (query_param_conflict). DuckDB's readers (read_json of a URL) do not send them." % ( "s" if len(out.get("param_names") or []) > 1 else "", "them" if len(out.get("param_names") or []) > 1 else "it")) if out.get("integration_id"): print("It sends the organisation's web key %s, read from the integration at each run: rotate the key there." % args.integration) else: print("The value is write-only: no command shows it. Use the URL in your SQL; the credential is added for you.") def cmd_sink_connection_list(args): out = request(args, "GET", "/v1/sql/connections?warehouse=%s" % urllib.parse.quote(resolve_catalog(args))) if _want_json(args): print_json(out) return emit(args, [_conn_row(c) for c in out.get("connections") or []], ["name", "url_prefix", "kind", "header", "updated"]) def cmd_sink_connection_replace(args): body = {"params": _query_params(args)} if args.param else {"value": _secret_value(args, "the new key")} if args.replace_all: if not args.param: die("--replace-all goes with --param (a query connection's parameters).", EXIT_USAGE) body["replace_all"] = True if args.header: body["header_name"] = args.header out = request(args, "PUT", "/v1/sql/connections/%s?warehouse=%s" % ( urllib.parse.quote(args.name), urllib.parse.quote(resolve_catalog(args))), body) if _want_json(args): print_json(out) return print("Connection %s: value replaced; the next preview or run uses it." % out["name"]) def cmd_sink_post_prefix_add(args): """POST /v1/sql/post-prefixes: let the catalog's scheduled SQL POST (http_post) under one URL prefix (#3001).""" out = request(args, "POST", "/v1/sql/post-prefixes", {"warehouse": resolve_catalog(args), "url_prefix": args.url_prefix}) if _want_json(args): print_json(out) return print("Catalog %s: scheduled SQL may now POST to URLs under %s (http_post). Every POST counts in the run's request " "budget and is recorded with its host." % (out.get("warehouse_name"), out["url_prefix"])) def cmd_sink_post_prefix_list(args): out = request(args, "GET", "/v1/sql/post-prefixes?warehouse=%s" % urllib.parse.quote(resolve_catalog(args))) if _want_json(args): print_json(out) return emit(args, [{"url_prefix": x["url_prefix"], "created": x.get("created_at")} for x in out.get("post_prefixes") or []], ["url_prefix", "created"]) def cmd_sink_post_prefix_remove(args): out = request(args, "DELETE", "/v1/sql/post-prefixes?warehouse=%s&url_prefix=%s" % ( urllib.parse.quote(resolve_catalog(args)), urllib.parse.quote(args.url_prefix, safe=""))) if _want_json(args): print_json(out) return print("Catalog: scheduled SQL may no longer POST under %s; a query that does is refused (post_not_declared)." % out["deleted"]) def cmd_sink_connection_delete(args): _confirm_irreversible(args, "Delete connection %s" % args.name) out = request(args, "DELETE", "/v1/sql/connections/%s?warehouse=%s" % ( urllib.parse.quote(args.name), urllib.parse.quote(resolve_catalog(args)))) if _want_json(args): print_json(out) return print("Connection %s deleted." % out["deleted"]) if out.get("paused_sinks"): print("Paused (their SQL names a URL under its prefix): %s. Resume with lhbox sink resume once they have a " "credential again." % ", ".join(out["paused_sinks"])) def _guess_content_type(name, data): low = (name or "").lower() if low.endswith(".csv"): return "text/csv" if low.endswith((".ndjson", ".jsonl")): return "application/x-ndjson" lines = [ln.strip() for ln in data.splitlines() if ln.strip()] if len(lines) > 1 and all(ln.startswith(b"{") and ln.endswith(b"}") for ln in lines): return "application/x-ndjson" # several one-line objects: NDJSON, whatever the file's name if low.endswith(".json") or data.lstrip()[:1] in (b"{", b"["): return "application/json" return "application/x-www-form-urlencoded" def _add_device_flags(c): g = c.add_argument_group("device intake") g.add_argument("--device", action="store_true", help="also give the sink a device route: a URL a device posts to with no " "header (form, JSON, NDJSON or CSV); saved with the send key") g.add_argument("--require-field", dest="require_field", metavar="FIELD=VALUE", help="a body field the device must send with " "this value (e.g. PASSKEY=...); hashed here, stripped before storage") g.add_argument("--strip", action="append", metavar="FIELD", help="a body field never stored (repeatable)") g.add_argument("--preset", metavar="NAME", help="a mapping shipped with the platform: ecowitt, ispindel, ttn (The Things Stack webhooks), sensor-community") g.add_argument("--param", action="append", metavar="NAME=VALUE", help="a preset's parameter, e.g. WS=ws-01 (repeatable)") g.add_argument("--mapping", metavar="FILE", help="a mapping document (JSON), validated against the table") def _sink_row_view(r): lag = r.get("lag") or {} last = r.get("last_roll") or {} return {"name": r.get("name"), "sink_id": r.get("sink_id"), "table": r.get("table"), "state": r.get("state"), "waiting": lag.get("batches_waiting"), "behind_s": lag.get("seconds_behind"), "last_roll": last.get("at") or "-", "rows": last.get("rows"), "rejected": (r.get("rejects") or {}).get("rows_total"), "created": r.get("created_at")} def cmd_sink_list(args): q = {} named = catalog_arg(args) if named: q["warehouse"] = named if args.all: q["include_deleted"] = "true" rows = request(args, "GET", "/v1/sinks" + ("?" + urllib.parse.urlencode(q) if q else ""))["sinks"] if _want_json(args): print_json(rows) return emit(args, [_sink_row_view(r) for r in rows], ["name", "sink_id", "table", "state", "waiting", "behind_s", "last_roll", "rows", "rejected", "created"], {"sink_id": "sink id", "behind_s": "behind (s)", "last_roll": "last roll", "rejected": "rejected rows"}) def cmd_sink_get(args): out = request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(args.sink)) emit(args, out) def cmd_sink_delete(args): cur = request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(args.sink)) waiting = int((cur.get("lag") or {}).get("batches_waiting") or 0) if waiting and not args.force: die("Sink %s has %d batch%s waiting that no roll has committed; deleting it DISCARDS them. Wait for the roll " "(lhbox sink get %s shows lag) or pass --force." % (cur.get("name"), waiting, "" if waiting == 1 else "es", cur["sink_id"]), EXIT_USAGE) _confirm_irreversible(args, "Delete sink %s (its send key is refused from now on)" % (cur.get("name") or cur["sink_id"])) out = request(args, "DELETE", "/v1/sinks/%s" % urllib.parse.quote(cur["sink_id"])) if _want_json(args): print_json(out) return print("Sink %s deleted: its send key is refused from now on; %d pending batch%s discarded; the table is untouched." % (out.get("name"), out.get("pending_batches_discarded", 0), "" if out.get("pending_batches_discarded") == 1 else "es")) def cmd_sink_dedupe(args): """POST /v1/sinks/{id}/dedupe (research/65 §2.4): the roller keeps only the latest row per key in the whole table, once; --wait polls until it has, and prints what it removed.""" cur = request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(args.sink)) if not cur.get("key"): die("Sink %s has no key: a dedupe keeps the latest row per key. Give it one first: lhbox sink update %s --key ." % (cur.get("name"), cur.get("name")), EXIT_USAGE) _confirm_irreversible(args, "Deduplicate %s: keep only the latest row per %s and remove every older one" % (cur.get("table"), ", ".join(cur["key"]))) out = request(args, "POST", "/v1/sinks/%s/dedupe" % urllib.parse.quote(cur["sink_id"]), {}) asked = (out.get("dedupe") or {}).get("requested_at") if not args.wait: if _want_json(args): print_json(out) else: print("Dedupe of %s asked for at %s. %s" % (out.get("table"), asked, out.get("note") or "")) return deadline = time.time() + args.timeout while time.time() < deadline: time.sleep(5) now = request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(cur["sink_id"])) d = now.get("dedupe") or {} last = d.get("last") or {} if d.get("requested_at") is None and last.get("requested_at") == asked: if _want_json(args): print_json(last) elif last.get("refused") or last.get("skipped") or last.get("failed"): print("Dedupe of %s not done: %s. %s" % (now.get("table"), last.get("refused") or last.get("skipped") or last.get("failed"), last.get("detail") or "")) else: print("Dedupe of %s done: %s of %s rows removed (%s file(s) dropped, %s rewritten), snapshot %s." % (now.get("table"), last.get("rows_removed"), last.get("rows_total"), last.get("files_deleted"), last.get("files_rewritten"), last.get("snapshot_id"))) if last.get("refused") or last.get("skipped") or last.get("failed"): sys.exit(1) # not done, whatever the reason return die("The roller has not answered the dedupe asked for at %s within %d s: lhbox sink get %s shows dedupe.requested_at " "until it does." % (asked, args.timeout, cur.get("name")), 1) def _send_key_for(args): """The send key: --send-key-file (the file `create --save` wrote; also gives the send URL), --send-key, or LHBOX_SEND_KEY. Never read from the credentials file: a send key is not the caller's identity.""" if args.send_key_file: saved = _file_arg(args.send_key_file, "--send-key-file", json_object=True, remedy="--send-key-file takes the JSON file `lhbox sink create --save` wrote.") if not isinstance(saved.get("send_key") or "", str) or not isinstance(saved.get("send_url") or "", str): die("%s is not a file `lhbox sink create --save` wrote: send_key and send_url are strings." % args.send_key_file, EXIT_USAGE) return saved.get("send_key"), saved.get("send_url"), saved.get("sink_id"), saved.get("name") key = args.send_key or os.environ.get("LHBOX_SEND_KEY") return key, None, None, None def cmd_sink_send(args): key, send_url, saved_id, saved_name = _send_key_for(args) sink = args.sink if saved_id and sink and (sink == saved_id or not UUID_RE.match(sink)): # the send route takes ids: a name is the file's own sink, or a usage error (it would answer 401 invalid_key) if sink not in (saved_id, saved_name): die("%s holds the send key of sink %s (%s), not %s: name that sink, or pass the file `sink create --save` " "wrote for %s." % (args.send_key_file, saved_name or "no name saved", saved_id, sink, sink), EXIT_USAGE) sink = None sink_id = sink or saved_id if not key: # no send key: this machine's own key, which the API accepts when it holds the sink's send grant or write on its # catalog (2026-10-02); a name is resolved to the id first (the send route takes ids) key = _api_key_or_none(args) if not key: die("No send key and no API key: pass --send-key-file , --send-key, set " "LHBOX_SEND_KEY, or log in with a key that holds the sink's send grant.", EXIT_USAGE) if sink_id and not UUID_RE.match(sink_id): sink_id = request(args, "GET", "/v1/sinks/%s" % urllib.parse.quote(sink_id))["sink_id"] # this machine's key goes only to --url, never to a send_url a file names (#3141) send_url = None if not sink_id: die("Name the sink: `lhbox sink send batch.json …` (the id is in the saved file too).", EXIT_USAGE) if args.file == "-": data = sys.stdin.buffer.read() else: data = _file_arg(args.file, "file", binary=True, remedy="Name the batch file to send (a JSON array), or - for stdin.") if not send_url or sink: send_url = "%s/v1/sinks/%s" % (args.url.rstrip("/"), urllib.parse.quote(sink_id)) batch_id = args.batch_id or str(uuid.uuid4()) req = urllib.request.Request(send_url, data=data, method="POST") req.add_unredirected_header("Authorization", "Bearer " + key) req.add_header("Content-Type", "application/json") req.add_header("Idempotency-Key", batch_id) try: with urllib.request.urlopen(req, timeout=120) as resp: status, raw = resp.status, resp.read() except (TimeoutError, socket.timeout): _die_timeout("POST", "/v1/sinks/%s" % sink_id, 120, idempotency_key=batch_id, idempotent=True) except urllib.error.HTTPError as e: status, raw = e.code, e.read() except urllib.error.URLError as e: _die_unreachable("POST", send_url, e.reason) except _LOST_ANSWER as e: _die_lost_or_bad_url("POST", "/v1/sinks/%s" % sink_id, e, idempotency_key=batch_id, idempotent=True) try: out = json.loads(raw) if raw else {} except ValueError: out = {"error": {"code": "http_%d" % status, "message": raw.decode(errors="replace")[:500]}} if status >= 400: # the same batch id is stored once (an Idempotency-Key the send route honours): re-sending it is the safe retry _fail("POST", "/v1/sinks/%s" % sink_id, status, out, idempotency_key=batch_id, idempotent=True) if _want_json(args): print_json(out) return if out.get("duplicate"): print("Batch %s was already received (%s): nothing written." % (out.get("batch_id"), out.get("state"))) else: print("Batch %s accepted: %d row%s stored, %d rejected at intake; committed at the next roll." % (out.get("batch_id"), out.get("accepted", 0), "" if out.get("accepted") == 1 else "s", out.get("rejected", 0))) for r in (out.get("reasons") or [])[:5]: print(" rejected element %s: %s" % (r.get("index"), r.get("reason"))) # ---------------------------------------------------------------- blob index rules: uploaded files become rows (research/32 §3) def _json_arg(value, what): """A JSON value given inline or as @file.""" text = _at_file(value, what) if value.startswith("@") else value try: return json.loads(text) except ValueError as e: die("%s is not valid JSON: %s" % (what, e), EXIT_USAGE) def cmd_index_create(args): rename = {} for r in args.rename or []: a, sep, b = r.partition("=") if not sep or not a or not b: die("--rename takes EXTRACTED=COLUMN, e.g. last_modified=uploaded_at.", EXIT_USAGE) rename[a] = b body = {"name": args.name, "warehouse": resolve_catalog(args), "prefix": args.prefix, "table": args.table, "extractors": _json_arg(args.extractors, "--extractors")} if rename: body["rename"] = rename if getattr(args, "ordered_keys", False): body["ordered_keys"] = True for field in ("poll_seconds", "roll_seconds", "inactivity_seconds"): if getattr(args, field, None) is not None: body[field] = getattr(args, field) out = request(args, "POST", "/v1/indexes", body) if _want_json(args): print_json(out) return cols = out.get("columns") or {} print("Index %s created: objects under %s of %s become rows of %s, found within %s s." % (out["name"], out.get("prefix") or "(the whole bucket)", out.get("bucket"), out["table"], out.get("poll_seconds"))) print(" stored columns: %s" % ", ".join(cols.get("stored") or [])) if cols.get("not_stored"): print(" not stored: %s (the table has no such column)" % ", ".join(cols["not_stored"])) print(" cost: no IAM write; the rows are committed by the roller like a sink's") print("Watch it: lhbox index get %s" % out["name"]) def _index_row_view(r): lag = ((r.get("sink") or {}).get("lag") or {}) return {"name": r.get("name"), "index_id": r.get("index_id"), "prefix": r.get("prefix"), "table": r.get("table"), "indexed": r.get("objects_indexed_total"), "last_poll": r.get("last_polled_at") or "-", "waiting": lag.get("batches_waiting"), "error": r.get("last_error") or ""} def cmd_index_list(args): q = {} named = catalog_arg(args) if named: q["warehouse"] = named rows = request(args, "GET", "/v1/indexes" + ("?" + urllib.parse.urlencode(q) if q else ""))["indexes"] if _want_json(args): print_json(rows) return emit(args, [_index_row_view(r) for r in rows], ["name", "index_id", "prefix", "table", "indexed", "last_poll", "waiting", "error"], {"index_id": "index id", "last_poll": "last poll", "waiting": "batches waiting"}) def cmd_index_get(args): emit(args, request(args, "GET", "/v1/indexes/%s" % urllib.parse.quote(args.index))) def cmd_index_delete(args): _confirm_irreversible(args, "Delete index %s (nothing more is indexed)" % args.index) out = request(args, "DELETE", "/v1/indexes/%s" % urllib.parse.quote(args.index)) if _want_json(args): print_json(out) return print("Index %s deleted: nothing more is indexed; the table, its rows and the files stay." % out.get("name")) def cmd_warehouse_list(args): """Every catalog the caller can see (all projects), or those of --project.""" if args.project: rows = request(args, "GET", "/v1/catalogs?" + urllib.parse.urlencode({"project": args.project}))["warehouses"] else: rows = _all_warehouses(args) # the version column: what `table create` without --format-version gives a new table there (v3 unless changed); # JSON keeps the API's integer, the table a person reads says v2 / v3. The storage columns come from the row's # `stored` block: the latest sample and how old it is ("measured 3 min ago"), "measuring..." while the first # measurement is on its way, "not yet" when the sweep has not been by (docs/usage-telemetry.md, "Freshness") if not _want_json(args): rows = [dict(r, default_format_version="v%s" % r["default_format_version"] if r.get("default_format_version") else "-", stored=_stored_human(r.get("stored")), measured=_measured_human(r.get("stored")), public_files_prefix=r.get("public_files_prefix") or "-") for r in rows] # general access: what a member of the organisation holds without a grant of their own (older servers: absent) rows = [dict(r, org_access={"none": "restricted", "read": "organisation"}.get(r.get("org_access"), "-")) for r in rows] # a catalog only LakehouseBox writes says so: `system` is the organisation's system catalog (lhbox), read-only rows = [dict(r, managed=r.get("managed") or "-") for r in rows] emit(args, rows, ["name", "warehouse_id", "my_level", "org_access", "managed", "project", "status", "public", "public_files_prefix", "default_format_version", "stored", "measured", "created_at"], {"warehouse_id": "catalog id", "default_format_version": "new tables", "public_files_prefix": "public files", "org_access": "general access", "managed": "kind"}) def _stored_human(st): if not st or st.get("unmetered"): return "measuring..." if st and st.get("measuring") else "not yet" return fmt_bytes(st.get("bytes")) + ("" if st.get("complete", True) else " (incomplete)") def _measured_human(st): if not st or not st.get("measured_at"): return "-" return _ago(st["measured_at"]) + ("" if (st.get("source") or "sweep") == "sweep" else " (%s)" % st["source"].replace("_", " ")) def _ago(iso): """'just now', '3 min ago', '2 h ago', '5 d ago' for an ISO-8601 UTC timestamp.""" try: then = datetime.datetime.fromisoformat(iso.replace("Z", "+00:00")) except (ValueError, AttributeError): return iso or "-" secs = max(0, (datetime.datetime.now(datetime.timezone.utc) - then).total_seconds()) if secs < 90: return "just now" if secs < 5400: return "%d min ago" % round(secs / 60) if secs < 172800: return "%d h ago" % round(secs / 3600) return "%d d ago" % round(secs / 86400) def cmd_warehouse_get(args): """GET /v1/catalogs/{id or name}: one catalog -- the row of `catalog list` plus the bucket (warehouse_name), the placement, `stored` (the latest storage figure and its freshness), `default_format_version` and `status` (ready | provisioning: the store has not accepted a write yet; the recipe answers 503 until it has).""" out = request(args, "GET", "/v1/catalogs/" + urllib.parse.quote(resolve_catalog(args), safe="")) if _want_json(args): emit(args, out) return st = out.get("stored") or {} rows = [("catalog", out.get("name")), ("catalog id", _cid(out)), ("project", "%s (%s)" % (out.get("project"), out.get("project_id"))), ("your level", (out.get("my_level") or "none") + (" via %s" % out["my_via"] if out.get("my_via") else "")), ("access", _general_access_human(out) if out.get("org_access") else "-"), ("status", out.get("status") or "ready"), ("new tables", "format version %s" % out.get("default_format_version") if out.get("default_format_version") else "-"), ("stored", _stored_human(st)), ("measured", _measured_human(st)), ("public", ("yes since %s" % out.get("public_since")) if out.get("public") else "no"), ("public files", ("%s (%s)" % (out["public_files_prefix"], out.get("public_files_url"))) if out.get("public_files_prefix") else "none"), ("bucket", out.get("warehouse_name")), ("catalog uri", out.get("catalog_uri")), ("placement", "%s %s" % (out.get("provider") or "-", out.get("region") or "")), ("created", out.get("created_at"))] for label, value in rows: print("%-12s %s" % (label, value)) if (out.get("status") or "ready") == "provisioning": print("\nStill provisioning: the storage refused the first write at creation; the control plane retries every 30 s for 10 min. " "Wait 30 s and run `lhbox doctor`; the recipe answers 503 until the status is ready.") def cmd_warehouse_measure(args): """POST /v1/catalogs/{id}/measure: the catalog's storage measured now (the store's own figure), not at the next reading.""" _, out = request_slow(args, "POST", "/v1/catalogs/%s/measure" % urllib.parse.quote(resolve_catalog(args)), what="measuring the catalog") if _want_json(args): emit(args, out) return print("catalog %s (%s)" % (out["name"], _cid(out))) print("stored %s in %s objects (tables %s, blobs %s)%s" % ( fmt_bytes(out["bytes"]), _all_objects(out), fmt_bytes(out["table_bytes"]), fmt_bytes(out["blob_bytes"]), " LOWER BOUND: the listing stopped at the page cap" if out.get("partial") else "")) for line in _sample_error_lines(out.get("errors"), out.get("complete", True)): print(line) print("measured %s (%s, %ss); the next reading replaces this figure by %s" % ( out["measured_at"], out["source"].replace("_", " "), out.get("seconds"), out["stale_after"])) st = out.get("storage") or {} if st.get("current") is not None: print("%-11s %s of %s (%s)" % (st.get("scope", "scope"), fmt_bytes(st["current"]), fmt_bytes(st["limit"]), "OVER THE LIMIT" if st.get("over_limit") else "headroom %s" % fmt_bytes(st.get("headroom")))) def cmd_warehouse_publish(args): """Storage-level public: one bucket policy, every object readable by anyone; the catalog is closed to anonymous callers and read-only by name to any account (the public-reader identity, research/38).""" rec = _unclaimed_in_use(args) if rec: # the server refuses it as claim_required whatever is confirmed: say that first, not "pass --confirm" (#1763) die_json("claim_required", "Nobody owns this organisation yet: publishing a catalog waits for a person to claim it.", EXIT_AUTH, expires_at=rec.get("expires_at"), remedy="Ask the person to claim it: `lhbox claim` prints the link and the code. Then run `lhbox catalog " "publish` again.") ref, confirm = confirmed_catalog(args, "publish", need_name=True) body = {"confirm": confirm} if getattr(args, "no_files", False): body["files"] = None # stop publishing files; the catalog stays public elif getattr(args, "files", None) is not None: body["files"] = args.files out = request(args, "POST", "/v1/catalogs/%s/public" % urllib.parse.quote(ref), body) if _want_json(args): print_json(out) return print("Catalog %s is PUBLIC since %s." % (out["name"], out.get("public_since"))) print(" public_url: %s" % out["public_url"]) if out.get("public_files_url"): print(" public_files_url: %s (the folder %s of the file bucket; the rest stays private)" % (out["public_files_url"], out.get("public_files_prefix"))) if out.get("public_files_s3_url") and out["public_files_s3_url"] != out["public_files_url"]: print(" public_files_s3_url: %s (the same folder at the S3 endpoint; photos are read here)" % out["public_files_s3_url"]) print(" " + out["public_note"]) print() _print_public_read(out.get("public_read") or {}) def cmd_warehouse_unpublish(args): ref, _ = confirmed_catalog(args, "unpublish", need_name=False) out = request(args, "DELETE", "/v1/catalogs/%s/public" % urllib.parse.quote(ref)) if _want_json(args): print_json(out) return print("Catalog %s is private%s. %s" % (out["name"], "" if out.get("was_public") else " (it already was)", out["note"])) def _print_public_read(recipe): if not recipe: return print("-- no credentials: paste into DuckDB") print(recipe.get("duckdb_sql", "")) if recipe.get("metadata_url"): print("-- current metadata file (changes on every commit): %s" % recipe["metadata_url"]) print("-- version hint (written by maintenance while public): %s" % recipe.get("version_hint_url")) print("-- " + recipe.get("note", "")) def cmd_warehouse_public_url(args): """The URLs a reader without an account uses, and the no-credentials DuckDB recipe. With --table, the current metadata URL of that table (the exact thing to paste into iceberg_scan).""" ref = resolve_catalog(args) if args.table: if "." not in args.table: die("--table wants .
", EXIT_USAGE) ns, name = args.table.rsplit(".", 1) out = request(args, "GET", "/v1/table?" + urllib.parse.urlencode({"catalog": ref, "namespace": ns, "name": name})) else: out = request(args, "GET", "/v1/connection?" + urllib.parse.urlencode({"catalog_id": ref, "engine": "duckdb"})) view = {k: out.get(k) for k in ("warehouse_id", "public", "public_since", "public_url", "public_url_in_cluster", "public_files_prefix", "public_files_url", "public_files_s3_url", "metadata_url", "version_hint_url", "public_note", "public_read") if k in out} if _want_json(args): print_json(view) return if not out.get("public"): name = out.get("warehouse") if args.table else out.get("catalog_alias") name = name if name and CATALOG_NAME_RE.match(str(name)) else (ref if not UUID_RE.match(ref) else "") print("This catalog is private: it has no public URL. Make it public (admin, the name typed out) with:") print(" lhbox catalog publish %s --confirm %s" % (name, name)) return print("public_url: %s (public since %s)" % (out["public_url"], out.get("public_since"))) if out.get("public_files_url"): print("public_files_url: %s (data files under %s, readable without credentials, range requests included)" % (out["public_files_url"], out.get("public_files_prefix"))) if out.get("public_files_s3_url") and out["public_files_s3_url"] != out["public_files_url"]: # the folder is read through the CDN (PLAN 29); photos are served at the S3 endpoint only print("public_files_s3_url: %s (the same folder at the S3 endpoint; photos are read here)" % out["public_files_s3_url"]) print(out.get("public_note", "")) print() _print_public_read(out.get("public_read") or {}) def catalog_arg(args): """The catalog named on the command line: the positional `` where a command takes one (2026-09-21: `catalog measure ` wanted --catalog), else `--catalog` / `--warehouse`; None when neither. Both, and different: a usage error rather than a guess.""" pos = getattr(args, "catalog_arg", None) flag = getattr(args, "warehouse", None) if pos and flag and pos != flag: die("Two catalogs named: %r and --catalog %r. Name one." % (pos, flag), EXIT_USAGE) return pos or flag def _own_catalogs(rows): """The catalogs a default is chosen among: the ones LakehouseBox does not write (no `managed` on the row), or all of them when it writes every one the caller can see.""" return [w for w in rows if not w.get("managed")] or rows def resolve_catalog(args): """The catalog named (positional or `--catalog`); otherwise the organisation's only catalog, the way `login` picks it (2026-09-20 night, item 1: an agent's first `connect` should not need a flag). One catalog visible: use it and say so on stderr. None: not found. Several: list them and stop with the usage code -- the caller has to choose, and a guess would silently point a session at the wrong data.""" named = catalog_arg(args) if named: args.warehouse = named return named rows = _all_warehouses(args) # a catalog LakehouseBox writes (the organisation's system catalog, lhbox) is never the default beside one of your # own: an admin with one catalog still has "the only catalog". It is the default only when it is all you can see own = _own_catalogs(rows) if len(own) == 1: w = own[0] print("Using your only catalog, %s (%s); --catalog names another." % (w.get("name"), _cid(w)), file=sys.stderr) args.warehouse = _cid(w) or w.get("name") return args.warehouse if not rows: die("No catalog is visible to this credential. Create one with `lhbox catalog create `, " "or ask an admin of your organisation for a grant.", EXIT_NOTFOUND) listing = "\n".join(" %-24s %s (%s)" % (w.get("name"), _cid(w), w.get("my_level") or "no grant") for w in rows) die("%d catalogs are visible; name one with --catalog :\n%s" % (len(rows), listing), EXIT_USAGE) def cmd_namespace_list(args): out = request(args, "GET", "/v1/namespaces?" + urllib.parse.urlencode({"catalog": resolve_catalog(args)})) emit(args, out["namespaces"], ["namespace"]) def cmd_table_list(args): q = {"catalog": resolve_catalog(args)} if args.namespace: q["namespace"] = args.namespace out = request(args, "GET", "/v1/tables?" + urllib.parse.urlencode(q)) emit(args, out["tables"], ["namespace", "name"]) if not _want_json(args) and sys.stderr.isatty(): print("(listed with the key from %s; lhbox whoami names its identity and organisation)" % key_source(args), file=sys.stderr) def _table_ref(args): """(namespace, name) of the ONE table a command acts on, from the positional `[catalog.]namespace.table` (the spelling MCP's describe_table and SQL use; the catalog part sets --catalog) or the hidden --namespace/--name the older command lines use (`credentials --table ` is --name there). Both given must agree; a three-part name and --catalog must name the same catalog; neither form is a usage error naming both (docs/proposals/cli-consistency.md §1, convention 1). A namespace holding a dot cannot be named positionally: three parts are catalog.namespace.table.""" pos = getattr(args, "table_ref", None) ns, name = getattr(args, "namespace", None), getattr(args, "name", None) if pos: parts = pos.split(".") if len(parts) not in (2, 3) or not all(p.strip() for p in parts) or "/" in pos: die("Name the table as [catalog.]namespace.table (got %r)." % pos, EXIT_USAGE) if len(parts) == 3: cat = parts[0] flag = catalog_arg(args) if flag and flag != cat: die("%r names catalog %r and --catalog names %r. Name one." % (pos, cat, flag), EXIT_USAGE) args.warehouse = cat pns, pname = parts[-2], parts[-1] if (ns and ns != pns) or (name and name != pname): die("%r and --namespace %r --name %r name different tables. Name one." % (pos, ns, name), EXIT_USAGE) return pns, pname if ns and name: return ns, name die("Name the table: [catalog.]namespace.table (or the older --namespace --name
).", EXIT_USAGE) def _table_catalog(args, verb): """The catalog a one-table command acts on (table get/create/set-properties/document, credentials): --catalog, the catalog part of catalog.namespace.table, or the only catalog, said on stderr, as `table list` and `table import` do (#1758: `ns.table` worked for import and was refused by the `table get` its own answer suggested). Only a drop insists on the name (_named_catalog_for_drop).""" return resolve_catalog(args) def _named_catalog_for_drop(args, verb): """A drop names its catalog: no "your only catalog" default (high review of #683, finding 6), as `catalog delete` names the catalog it deletes. A guess is harmless for a read and not for a purge.""" ref = catalog_arg(args) if not ref: die("Name the catalog: lhbox %s --catalog (a drop never defaults to your only catalog)." % verb, EXIT_USAGE) args.warehouse = ref return ref def _confirm_drop(args, what, ref): """The guard every drop goes through, before any request that changes something: a PUBLIC catalog refuses without --force (its public URL stops serving what is dropped), then a terminal is asked [y/N] unless --yes; without a terminal and without --yes it refuses rather than wait for an answer that cannot come. Returns the API body extra.""" cat = request(args, "GET", "/v1/catalogs/" + urllib.parse.quote(ref, safe="")) name = cat.get("name") or ref if cat.get("public") and not args.force: die("Catalog %s is public: dropping %s stops its public URL serving it to every reader without an account. " "Pass --force to drop it anyway, or unpublish the catalog first (lhbox catalog unpublish %s)." % (name, what, name), EXIT_USAGE) if not args.yes: # ask only a person at a terminal on both ends; a script reading stdout (piped, or --json) must neither get the # question there nor wait for an answer (high review of #683, finding 3). The question goes to stderr. if not (sys.stdin.isatty() and sys.stdout.isatty()) or args.json: die("Dropping %s in catalog %s cannot be undone; pass --yes to confirm (not asked: no terminal, or --json)." % (what, name), EXIT_USAGE) sys.stderr.write("Drop %s in catalog %s? Its data files are deleted; this cannot be undone. [y/N] " % (what, name)) sys.stderr.flush() ans = input("") if ans.strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was dropped.", EXIT_USAGE) return {"force": True} if args.force else {} def cmd_table_delete(args): """Drop one table (DELETE /v1/table: the catalog's DROP with purge, as the catalog's own identity; write holders).""" ns, name = _table_ref(args) ref = _named_catalog_for_drop(args, "table delete %s.%s" % (ns, name)) extra = _confirm_drop(args, "table %s.%s" % (ns, name), ref) out = request(args, "DELETE", "/v1/table", {"catalog_id": ref, "namespace": ns, "name": name, **extra}) if not _want_json(args): print("dropped %s from catalog %s" % (out.get("dropped"), out.get("catalog"))) return print_json(out) def cmd_namespace_delete(args): """Drop one EMPTY namespace (DELETE /v1/namespace). A namespace with tables is the API's 409 naming them: nothing is cascaded, drop each table first with `lhbox table delete`.""" ref = _named_catalog_for_drop(args, "namespace delete %s" % args.namespace_ref) extra = _confirm_drop(args, "namespace %s" % args.namespace_ref, ref) out = request(args, "DELETE", "/v1/namespace", {"catalog_id": ref, "namespace": args.namespace_ref, **extra}) if not _want_json(args): print("dropped namespace %s from catalog %s" % (out.get("dropped"), out.get("catalog"))) return print_json(out) def cmd_table_get(args): ns, name = _table_ref(args) q = {"catalog": _table_catalog(args, "table get"), "namespace": ns, "name": name} out = request(args, "GET", "/v1/table?" + urllib.parse.urlencode(q)) for w in out.get("warnings", []): print("warning: " + _visible(w), file=sys.stderr) want_json = args.json or (not args.human and not sys.stdout.isatty()) if want_json: print_json(out) return # For a human the schema is the point, so print the scalars and then the columns as a table. for k in ("table", "warehouse", "warehouse_id", "table_uuid", "format_version", "location", "snapshots", "rows"): v = out.get(k) if k == "rows" and _rows_known(out) is None: v = ROWS_NOT_AVAILABLE if v is None else "%s (not exact)" % v print("%-26s %s" % ({"warehouse": "catalog", "warehouse_id": "catalog id"}.get(k, k), _visible(v))) if out.get("doc"): print("%-26s %s" % ("doc", _visible(out["doc"]))) print() rows = [dict(r, identifier=r["id"] in out.get("identifier_field_ids", []), doc=r.get("doc") or "") for r in out.get("schema", [])] # the column docs `table document` writes (#1762: they were in the JSON and on MCP, never here); no column for none emit(argparse.Namespace(json=False, human=True), rows, ["id", "name", "type", "required", "identifier"] + (["doc"] if any(r.get("doc") for r in rows) else [])) props = out.get("properties") or {} if props: # the table's properties (geo.* for an imported GeoParquet, docs/engines): the long values shortened print() print("properties") for k in sorted(props): v = str(props[k]) print(" %-24s %s" % (_visible(k), _visible(v if len(v) <= 100 else v[:97] + "..."))) for line in clustering_lines(out.get("clustering")): print(_visible(line)) def clustering_lines(c): """A geometry table's `clustering` (GET /v1/table, research/91 G1) for a human: the column the store keeps the table in spatial order by, and what a point lookup reads now. Nothing for a table without a geometry column.""" if not c: return [] out = ["", "spatial clustering"] if c.get("maintained"): out.append(" %-24s %s (kept in spatial order by maintenance)" % ("column", c.get("column"))) else: why = {"opted_out": "%s is none" % c.get("property"), "sort_order": "the table declares a sort order", "several_geometry": "several geometry columns: name one in %s" % c.get("property"), "named_not_found": "%s names no geometry column" % c.get("property")}.get(c.get("reason"), c.get("reason")) out.append(" %-24s %s (not maintained: %s)" % ("column", c.get("column") or "-", why)) if c.get("state") is None: return out out.append(" %-24s %s" % ("state", c["state"])) held = c.get("held_open") if held: # #1831: maintenance leaves an open day or hour partition as written until it has ended plus 2 hours out.append(" %-24s %s (%s, %s file(s)): kept as written until %s, then compacted in spatial order; the state " "counts these files" % ("held open", ", ".join(held.get("partitions") or []), held.get("field"), held.get("files"), held.get("release_at"))) if c.get("lookup_cost") is not None: out.append(" %-24s %s row groups' worth, %.1f %% of the geometry column (%s row groups in %s files)" % ("a point lookup reads", c["lookup_cost"], 100 * (c.get("lookup_share") or 0), c.get("row_groups"), c.get("files"))) sampled = c.get("sampled") if sampled: out.append(" %-24s %s of %s files' footers" % ("measured on", sampled.get("files_read"), sampled.get("of"))) if c.get("files_without_bounds"): out.append(" %-24s %s (every lookup reads them)" % ("files without bounds", c["files_without_bounds"])) if c.get("last_spatial_compaction"): out.append(" %-24s %s; %s file(s), %s row(s) added since" % ("last re-clustered", c["last_spatial_compaction"], c.get("files_added_since"), c.get("rows_added_since"))) return out def cmd_table_set_properties(args): props = {} for spec in args.property or []: k, sep, v = spec.partition("=") if not sep or not k.strip(): die_json("bad_property", "--property wants key=value, got %r" % spec, EXIT_USAGE, remedy="--property geo.crs=EPSG:4326 (repeatable); --remove drops one") props[k.strip()] = v ns, name = _table_ref(args) body = {"catalog_id": _table_catalog(args, "table set-properties"), "namespace": ns, "name": name} if props: body["properties"] = props if args.remove: body["remove"] = list(args.remove) if not props and not args.remove: die_json("nothing_to_change", "Give --property key=value and/or --remove key.", EXIT_USAGE) emit(args, request(args, "PATCH", "/v1/table", body)) _MISSING_DOC = object() # --------------------------------------------------------------------------- lhbox migrate (tablemere#3007, PLAN 21) # Tables come into a declared setup through migrations, not as resources (PLAN 21: a provider that owns tables fights # every other writer): numbered files `NNN_.sql` of plain DuckDB DDL, each applied once, in order, and recorded in # the catalog (GET/PUT /v1/catalogs/{id}/migrations, with each file's checksum). What a file may hold is schema and its # description, never rows or a drop: CREATE SCHEMA, CREATE TABLE [IF NOT EXISTS] (made through POST /v1/tables, so the # catalog's rules hold: format version, partition, the layout properties), COMMENT ON TABLE / COLUMN (PATCH /v1/table). # What DuckDB DDL cannot say goes on a comment line right above the CREATE TABLE: # -- lhbox: format-version=3 partition=day(observed_at) # A table that already exists is left as it is (its differences from the file are reported, never applied), so a first # `migrate` against a catalog built by hand records its files without touching a row. Every statement of every pending # file is read and checked before anything is sent. MIGRATION_FILE = re.compile(r"^(\d{1,9})_[A-Za-z0-9_.-]+\.sql$") MIGRATE_DIRECTIVE = re.compile(r"^\s*--\s*lhbox:\s*(.*)$", re.I) MIGRATE_DIRECTIVE_PAIR = re.compile(r"([A-Za-z][A-Za-z0-9_-]*)=((?:\s*,\s*|\([^()]*\)|[^\s(=,])+)") MIGRATE_ADD_COLUMNS_MAX = 50 # PATCH /v1/table's add_columns per request (read_verbs.ADD_COLUMNS_MAX) MIGRATE_STAMP = "__ingest_ts" # a sink's own column: never a difference worth reporting def _sql_statements(text): """[(statement, directives, line)] of one SQL file: split at semicolons outside quotes and comments; a statement's directives are the `-- lhbox:` lines between the previous statement and it.""" out, buf, directives, i, n, line, start_line = [], [], {}, 0, len(text), 1, None while i < n: ch = text[i] if ch == "-" and text.startswith("--", i): j = text.find("\n", i) j = n if j < 0 else j m = MIGRATE_DIRECTIVE.match(text[i:j]) if m: # key=value pairs; a value may hold spaces inside parentheses (partition=bucket(16, id), day(ts)) body = m.group(1).strip() for pm in MIGRATE_DIRECTIVE_PAIR.finditer(body): directives[pm.group(1).lower()] = re.sub(r"\s*,\s*", ",", pm.group(2).strip()).replace(",", ", ") if MIGRATE_DIRECTIVE_PAIR.sub("", body).strip(): raise ValueError("line %d: a directive is key=value (format-version=3 partition=day(ts)), got %r" % (line, body)) buf.append(" ") i = j continue if ch == "/" and text.startswith("/*", i): j = text.find("*/", i + 2) if j < 0: raise ValueError("line %d: a /* comment is never closed" % line) line += text.count("\n", i, j + 2) buf.append(" ") i = j + 2 continue if ch in "'\"": j = i + 1 while True: j = text.find(ch, j) if j < 0: raise ValueError("line %d: a %s quote is never closed" % (line, "single" if ch == "'" else "double")) if text.startswith(ch * 2, j): j += 2 continue break if start_line is None: start_line = line line += text.count("\n", i, j + 1) buf.append(text[i:j + 1]) i = j + 1 continue if ch == ";": stmt = "".join(buf).strip() if stmt: out.append((stmt, directives, start_line or line)) elif directives: raise ValueError("line %d: a `-- lhbox:` directive stands before no statement" % line) buf, directives, start_line = [], {}, None i += 1 continue if ch == "\n": line += 1 elif not ch.isspace() and start_line is None: start_line = line buf.append(ch) i += 1 rest = "".join(buf).strip() if rest: out.append((rest, directives, start_line or line)) return out def _sql_name_parts(text): """'embalses."now".rain_grid' -> ['embalses', 'now', 'rain_grid'], and the rest of the text after the name.""" parts, i, n = [], 0, len(text) while True: while i < n and text[i].isspace(): i += 1 if i < n and text[i] == '"': j = i + 1 while True: j = text.find('"', j) if j < 0: raise ValueError("a quoted name is never closed") if text.startswith('""', j): j += 2 continue break parts.append(text[i + 1:j].replace('""', '"')) i = j + 1 else: m = re.match(r"[A-Za-z_][A-Za-z0-9_$]*", text[i:]) if not m: raise ValueError("expected a name at %r" % text[i:i + 30]) parts.append(m.group(0).lower()) i += m.end() while i < n and text[i].isspace(): i += 1 if i < n and text[i] == ".": i += 1 continue return parts, text[i:] def _sql_literal(text): """The value of one SQL string literal ('it''s' -> it's) that is the whole of `text`, or ValueError.""" t = text.strip() if len(t) < 2 or t[0] != "'" or t[-1] != "'" or "'" in t[1:-1].replace("''", ""): raise ValueError("expected one string literal, got %r" % t[:40]) return t[1:-1].replace("''", "'") def _migrate_table_ref(parts, alias, what): """(namespace, table) from a name of 2 parts, or of 3 whose first part is the files' catalog name (`alias`).""" if len(parts) == 3: if alias[0] is None: alias[0] = parts[0] elif parts[0] != alias[0]: raise ValueError("%s names catalog %r, another statement %r: the files of one directory are for one catalog" % (what, parts[0], alias[0])) parts = parts[1:] if len(parts) != 2: raise ValueError("%s: name the table as namespace.table or catalog.namespace.table" % what) return parts[0], parts[1] # DuckDB's DDL spellings of a type -> the one DESCRIBE prints (what duckdb_type_to_iceberg reads) _DDL_TYPE_ALIASES = [(r"TIMESTAMPTZ", "TIMESTAMP WITH TIME ZONE"), (r"DATETIME", "TIMESTAMP"), (r"INT4|INT|SIGNED", "INTEGER"), (r"INT8|LONG", "BIGINT"), (r"INT2|SHORT", "SMALLINT"), (r"INT1", "TINYINT"), (r"BOOL|LOGICAL", "BOOLEAN"), (r"FLOAT4|REAL", "FLOAT"), (r"FLOAT8", "DOUBLE"), (r"TEXT|STRING|BPCHAR|CHAR", "VARCHAR"), (r"BYTEA|BINARY|VARBINARY", "BLOB"), (r"NUMERIC", "DECIMAL")] def _ddl_type(t): """A column's type as written in DDL -> DESCRIBE's spelling: aliases replaced, VARCHAR(n) -> VARCHAR, outside quotes and outside STRUCT field names (STRUCT(lat DOUBLE, long DOUBLE) keeps its field `long`).""" m = next((m for m in re.finditer(r"'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|(?i:\bSTRUCT\s*\()", t) if m.group(0)[0] not in "'\""), None) if m: depth, quote, end = 1, None, len(t) for j in range(m.end(), len(t)): ch = t[j] if quote: quote = None if ch == quote else quote elif ch in "'\"": quote = ch elif ch in "()": depth += 1 if ch == "(" else -1 if not depth: end = j break fields = [] for f in _split_top_level(t[m.end():end]): q = re.match(r'\s*("(?:[^"]|"")*"|\S+)', f) fields.append(q.group(1) + " " + _ddl_type(f[q.end():]) if q else f) return (_ddl_type_flat(t[:m.start()]) + "STRUCT(" + ", ".join(fields) + ")" + _ddl_type(t[end + 1:])).strip() return _ddl_type_flat(t).strip() def _ddl_type_flat(t): out, i = [], 0 for m in re.finditer(r"'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"", t): out.append(_ddl_type_bare(t[i:m.start()])) out.append(m.group(0)) i = m.end() out.append(_ddl_type_bare(t[i:])) return "".join(out) def _ddl_type_bare(t): t = re.sub(r"(?i)\bVARCHAR\s*\(\s*\d+\s*\)", "VARCHAR", t) for alias, canon in _DDL_TYPE_ALIASES: t = re.sub(r"(?i)\b(?:%s)\b(?!\s+WITH)" % alias, canon, t) t = re.sub(r"(?i)\bDOUBLE\s+PRECISION\b", "DOUBLE", t) return re.sub(r"(?i)\bTIMESTAMP\s+WITH\s+TIME\s+ZONE\b", "TIMESTAMP WITH TIME ZONE", t) def _migrate_columns(body): """'(a INTEGER NOT NULL, g GEOMETRY, l VARCHAR[])' -> [(name, duckdb type, required)].""" body = body.strip() if not (body.startswith("(") and body.endswith(")")): raise ValueError("CREATE TABLE needs its column list in parentheses (CREATE TABLE … AS SELECT writes rows: not here)") cols = [] for item in _split_top_level(body[1:-1]): item = item.strip() if not item: continue if re.match(r"(?i)(PRIMARY\s+KEY|UNIQUE|CHECK|FOREIGN\s+KEY|CONSTRAINT)\b", item): raise ValueError("table constraints (%s) have no Iceberg form" % item.split()[0].upper()) parts, rest = _sql_name_parts(item) if len(parts) != 1: raise ValueError("a column name is one name, got %r" % item[:40]) rest = rest.strip() required = False m = re.search(r"(?i)\s+NOT\s+NULL\s*$", " " + rest) if m: required, rest = True, (" " + rest)[:m.start()].strip() if re.search(r"(?i)\b(DEFAULT|PRIMARY|UNIQUE|CHECK|REFERENCES|GENERATED|COLLATE)\b", rest): raise ValueError("column %s: only a type and NOT NULL (no DEFAULT, keys or constraints)" % parts[0]) if not rest: raise ValueError("column %s has no type" % parts[0]) cols.append((parts[0], _ddl_type(rest), required)) if not cols: raise ValueError("CREATE TABLE with no columns") return cols def _migrate_plan_file(text, alias): """One file's statements as actions: [{kind, namespace, table, ...}]. ValueError (with its line) for anything that is not schema DDL.""" actions = [] for stmt, directives, line in _sql_statements(text): try: head = " ".join(stmt.split()[:4]).upper() if re.match(r"(?is)^CREATE\s+SCHEMA\b", stmt): rest = re.sub(r"(?is)^CREATE\s+SCHEMA\s+(IF\s+NOT\s+EXISTS\s+)?", "", stmt) parts, tail = _sql_name_parts(rest) if tail.strip(): raise ValueError("CREATE SCHEMA takes a name only") if len(parts) == 2: _migrate_table_ref(parts + ["x"], alias, "CREATE SCHEMA") parts = parts[1:] actions.append({"kind": "namespace", "namespace": parts[0], "line": line}) elif re.match(r"(?is)^CREATE\s+(OR\s+REPLACE\s+)?(TEMP|TEMPORARY\s+)?TABLE\b", stmt): if re.match(r"(?is)^CREATE\s+(OR\s+REPLACE|TEMP)", stmt): raise ValueError("CREATE OR REPLACE and TEMP tables replace or vanish: CREATE TABLE [IF NOT EXISTS] only") rest = re.sub(r"(?is)^CREATE\s+TABLE\s+(IF\s+NOT\s+EXISTS\s+)?", "", stmt) parts, body = _sql_name_parts(rest) ns, table = _migrate_table_ref(parts, alias, "CREATE TABLE") cols = _migrate_columns(body) unknown = sorted(set(directives) - {"format-version", "partition"}) if unknown: raise ValueError("unknown directive %s (format-version, partition)" % ", ".join(unknown)) fv = directives.get("format-version") if fv is not None and fv not in ("2", "3"): raise ValueError("format-version is 2 or 3, got %r" % fv) partition = [p.strip() for p in _split_top_level(directives["partition"])] if directives.get("partition") else [] actions.append({"kind": "table", "namespace": ns, "table": table, "columns": cols, "format_version": int(fv) if fv else None, "partition": partition, "line": line}) elif re.match(r"(?is)^ALTER\s+TABLE\b", stmt): # additive only: ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] c TYPE (an optional column: no NOT NULL) if_exists = bool(re.match(r"(?is)^ALTER\s+TABLE\s+IF\s+EXISTS\b", stmt)) rest = re.sub(r"(?is)^ALTER\s+TABLE\s+(IF\s+EXISTS\s+)?", "", stmt) parts, tail = _sql_name_parts(rest) ns, table = _migrate_table_ref(parts, alias, "ALTER TABLE") m = re.match(r"(?is)^\s*ADD\s+(COLUMN\s+)?(IF\s+NOT\s+EXISTS\s+)?(.*)$", tail) if not m: raise ValueError("ALTER TABLE only adds a column here (ADD COLUMN name TYPE): renaming, dropping or " "retyping a column rewrites what its readers expect") (cname, ctype, required), = _migrate_columns("(" + m.group(3) + ")") if required: raise ValueError("an added column is optional (its rows so far have no value): drop NOT NULL") try: # a type with no Iceberg form is refused now, not mid-apply schema_from_describe([{"column_name": cname, "column_type": ctype}], 3) except ValueError as exc: raise ValueError("column %s: %s" % (cname, exc.args[1] if len(exc.args) > 1 else exc)) actions.append({"kind": "add_column", "namespace": ns, "table": table, "column": cname, "type": ctype, "if_exists": if_exists, "line": line}) elif re.match(r"(?is)^COMMENT\s+ON\s+(TABLE|COLUMN)\b", stmt): what = re.match(r"(?is)^COMMENT\s+ON\s+(TABLE|COLUMN)\s+", stmt) parts, tail = _sql_name_parts(stmt[what.end():]) m = re.match(r"(?is)^\s*IS\s+(.*)$", tail) if not m: raise ValueError("COMMENT ON … IS ''") value = None if m.group(1).strip().upper() == "NULL" else _sql_literal(m.group(1)) if what.group(1).upper() == "TABLE": ns, table = _migrate_table_ref(parts, alias, "COMMENT ON TABLE") actions.append({"kind": "doc", "namespace": ns, "table": table, "doc": value, "line": line}) else: if len(parts) < 3: raise ValueError("COMMENT ON COLUMN names namespace.table.column") ns, table = _migrate_table_ref(parts[:-1], alias, "COMMENT ON COLUMN") actions.append({"kind": "column_doc", "namespace": ns, "table": table, "column": parts[-1], "doc": value, "line": line}) else: raise ValueError("%s… is not a migration statement: CREATE SCHEMA, CREATE TABLE, ALTER TABLE … ADD COLUMN, " "COMMENT ON TABLE/COLUMN (nothing that writes or drops rows or tables)" % head[:40]) except ValueError as exc: raise ValueError("line %d: %s" % (line, exc)) from None if directives and actions[-1]["kind"] != "table": raise ValueError("line %d: a `-- lhbox:` directive goes right above a CREATE TABLE" % line) per_table: dict = {} for a in actions: if a["kind"] == "add_column": per_table[(a["namespace"], a["table"])] = per_table.get((a["namespace"], a["table"]), 0) + 1 for (ns, table), n in per_table.items(): if n > MIGRATE_ADD_COLUMNS_MAX: raise ValueError("%s.%s: %d columns added in one file; at most %d (split them across files)" % (ns, table, n, MIGRATE_ADD_COLUMNS_MAX)) return actions def _migrate_files(directory): """[(version, name, path)] of NNN_*.sql in `directory`, by version; ValueError for two files of one version.""" try: names = sorted(os.listdir(directory)) except OSError as exc: die_json("migrations_unreadable", "Cannot read %s: %s" % (directory, exc.strerror or exc), EXIT_USAGE, directory=directory, remedy="--dir names the folder of NNN_.sql files (default sql/migrations).") files, seen = [], {} for name in names: m = MIGRATION_FILE.match(name) if not m: continue v = int(m.group(1)) if v < 1: die_json("bad_migration_name", "%s: versions start at 1 (001_.sql)." % name, EXIT_USAGE) if v in seen: die_json("duplicate_migration", "%s and %s have the same version %d." % (seen[v], name, v), EXIT_USAGE) seen[v] = name files.append((v, name, os.path.join(directory, name))) return sorted(files) def _migrate_checksum(data): return "sha256:" + hashlib.sha256(data.replace(b"\r\n", b"\n")).hexdigest() def _iceberg_name_type(t): """A comparable spelling of an Iceberg type (a nested type by its JSON without ids, requiredness and docs, as the server's read_verbs._same_type compares).""" if isinstance(t, dict): return json.dumps({k: _iceberg_name_type(v) for k, v in t.items() if not (k.endswith("id") or k.endswith("required") or k == "doc")}, sort_keys=True) if isinstance(t, list): return json.dumps([_iceberg_name_type(x) for x in t]) return str(t).replace(" ", "").lower() def cmd_migrate(args): """Apply the catalog's pending migrations (see the block comment above).""" report = migrate_run(args, resolve_catalog(args), args.dir, bool(args.dry_run), bool(args.repair)) if _want_json(args): print_json(report) return for f in report["files"]: acts = f.get("actions") or [] made = sum(1 for x in acts if x["action"] == "create") print("%-5s %-32s %s%s" % (f["version"], f["file"], f["state"], (": %d table(s) made, %d described" % (made, sum(1 for x in acts if x["action"] == "describe"))) if acts else "")) for d in report["differences"]: print("difference: %s %s" % (d["table"], json.dumps({k: v for k, v in d.items() if k != "table" and v})), file=sys.stderr) if args.dry_run: print("dry run: nothing was sent.", file=sys.stderr) def migrate_run(args, catalog, directory, dry_run, repair): """The report of `lhbox migrate` (and of `lhbox plan|apply`'s migrations): with dry_run, what would run.""" args.dry_run, args.repair = dry_run, repair files = _migrate_files(directory) if not files: die_json("no_migrations", "No NNN_.sql file in %s." % directory, EXIT_USAGE, directory=directory) listed = request(args, "GET", "/v1/catalogs/%s/migrations" % urllib.parse.quote(catalog)) wid, cname = listed.get("warehouse_id") or catalog, listed.get("name") applied = {int(m["version"]): m for m in listed.get("migrations") or []} alias, plans, report = [None], [], {"catalog": cname, "catalog_id": wid, "directory": directory, "dry_run": bool(args.dry_run), "files": [], "differences": []} for v, name, path in files: with open(path, "rb") as fh: data = fh.read() checksum = _migrate_checksum(data) rec = applied.get(v) entry = {"version": v, "file": name, "checksum": checksum} if rec and rec["checksum"] == checksum: # the same file (a rename keeps its checksum: it ran, under the name it had then) report["files"].append(dict(entry, state="applied", applied_at=rec.get("applied_at"), **({"recorded_as": rec["name"]} if rec["name"] != name else {}))) continue if rec and not args.repair: die_json("checksum_mismatch", "%s ran against catalog %s on %s as another file (recorded %s). A migration " "that ran is never edited." % (name, cname, rec.get("applied_at"), rec["checksum"]), EXIT_ERROR, version=v, file=name, checksum=checksum, recorded=rec, remedy="Add a new numbered file for the change. If the edit only rewrote what already holds " "(comments, formatting), record the files as they are now: lhbox migrate --repair.") try: text = data.decode("utf-8") actions = _migrate_plan_file(text, alias) except (UnicodeDecodeError, ValueError) as exc: die_json("bad_migration", "%s: %s" % (name, exc), EXIT_USAGE, file=name, remedy="A migration holds CREATE SCHEMA, CREATE TABLE [IF NOT EXISTS] (with `-- lhbox: format-version=N " "partition=(col)` above it), COMMENT ON TABLE/COLUMN; nothing that writes or drops.") plans.append((v, name, checksum, actions, bool(rec))) if alias[0] and alias[0] not in (cname, catalog): print("note: the files name catalog %r; applying them to %s" % (alias[0], cname), file=sys.stderr) for v, name, checksum, actions, repairing in plans: entry = {"version": v, "file": name, "checksum": checksum, "state": "repair" if repairing else "pending", "actions": []} report["files"].append(entry) if repairing: # --repair records the file as it is now: what it declares already holds (its tables exist), so nothing runs entry["actions"].append({"action": "record", "repair": True}) if not args.dry_run: request(args, "PUT", "/v1/catalogs/%s/migrations/%d" % (urllib.parse.quote(wid), v), {"name": name, "checksum": checksum, "repair": True}) entry["state"] = "repaired" continue docs: dict = {} adds: dict = {} for a in actions: key = (a["namespace"], a["table"]) if a["kind"] != "namespace" else None if a["kind"] == "namespace": entry["actions"].append({"action": "namespace", "namespace": a["namespace"], "note": "made with its first table"}) elif a["kind"] == "table": st, cur = request_status(args, "GET", "/v1/table?" + urllib.parse.urlencode( {"warehouse": wid, "namespace": a["namespace"], "name": a["table"]})) try: schema = schema_from_describe([{"column_name": c, "column_type": t} for c, t, _ in a["columns"]], a["format_version"] or 3) except ValueError as exc: die_json("bad_migration", "%s line %d: column %s: %s" % (name, a["line"], exc.args[0], exc.args[1] if len(exc.args) > 1 else exc), EXIT_USAGE, file=name) for f, (_, _, req) in zip(schema["fields"], a["columns"]): f["required"] = req ref = "%s.%s" % key if st == 200: have = {c.get("name"): c for c in cur.get("schema") or []} want = {f["name"]: f for f in schema["fields"]} diff = {"table": ref, "missing_in_catalog": sorted(n for n in want if n not in have and n != MIGRATE_STAMP), "not_in_file": sorted(n for n in have if n not in want and n != MIGRATE_STAMP), "other_type": sorted(n for n in want if n in have and n != MIGRATE_STAMP and _iceberg_name_type(want[n]["type"]) != _iceberg_name_type(have[n].get("type")))} if a["format_version"] and cur.get("format_version") and int(cur["format_version"]) != a["format_version"]: diff["format_version"] = {"file": a["format_version"], "catalog": int(cur["format_version"])} if any(diff[k] for k in ("missing_in_catalog", "not_in_file", "other_type")) or "format_version" in diff: report["differences"].append(diff) entry["actions"].append({"action": "exists", "table": ref}) continue if st != 404: die_json("catalog_unreadable", "Could not read %s (HTTP %d)." % (ref, st), EXIT_SERVER, table=ref) entry["actions"].append({"action": "create", "table": ref, "format_version": a["format_version"], "partition": a["partition"] or None, "columns": len(schema["fields"])}) if not args.dry_run: body = {"catalog_id": wid, "namespace": a["namespace"], "name": a["table"], "schema": schema} if a["format_version"]: body["format_version"] = a["format_version"] if a["partition"]: body["partition"] = a["partition"] request(args, "POST", "/v1/tables", body) elif a["kind"] == "add_column": adds.setdefault(key, []).append(a) elif a["kind"] == "doc": docs.setdefault(key, {"doc": _MISSING_DOC, "columns": {}})["doc"] = a["doc"] else: docs.setdefault(key, {"doc": _MISSING_DOC, "columns": {}})["columns"][a["column"]] = a["doc"] for (ns, table), cols in adds.items(): # one commit per table per file, the added columns' descriptions in it (COMMENT ON COLUMN of a column this # file adds); typed with the table's own format version (TIMESTAMP_NS is timestamp on a v2 table) ref = "%s.%s" % (ns, table) live = _get_ok(args, "/v1/table?" + urllib.parse.urlencode({"warehouse": wid, "namespace": ns, "name": table}), ok404=True) made_now = any(x.get("action") == "create" and x.get("table") == ref for x in entry["actions"]) if live is None and not made_now: if all(a["if_exists"] for a in cols): entry["actions"].append({"action": "skip", "table": ref, "why": "ALTER TABLE IF EXISTS: no such table"}) continue die_json("table_not_found", "%s: ALTER TABLE %s, which does not exist." % (name, ref), EXIT_NOTFOUND, file=name) fv = int((live or {}).get("format_version") or next((a["format_version"] for a in actions if a["kind"] == "table" and (a["namespace"], a["table"]) == (ns, table) and a["format_version"]), None) or 3) typed = schema_from_describe([{"column_name": a["column"], "column_type": a["type"]} for a in cols], fv) col_docs = (docs.get((ns, table)) or {}).get("columns") or {} body_cols = [] for f in typed["fields"]: c = {"name": f["name"], "type": f["type"]} if col_docs.get(f["name"]): c["doc"] = col_docs.pop(f["name"]) # described in the same commit body_cols.append(c) body = {"catalog_id": wid, "namespace": ns, "name": table, "add_columns": body_cols} entry["actions"].append({"action": "add_columns", "table": ref, "columns": [a["column"] for a in cols]}) if not args.dry_run: out = request(args, "PATCH", "/v1/table", body) entry["actions"][-1]["added"] = out.get("columns_added") for (ns, table), d in docs.items(): ref = "%s.%s" % (ns, table) if d["doc"] is _MISSING_DOC and not d["columns"]: continue # every description went with its added column body = {"catalog_id": wid, "namespace": ns, "name": table} if d["doc"] is not _MISSING_DOC: body["doc"] = d["doc"] if d["columns"]: body["column_docs"] = d["columns"] entry["actions"].append({"action": "describe", "table": ref, "table_doc": "doc" in body, "columns": len(d["columns"])}) if not args.dry_run: request(args, "PATCH", "/v1/table", body) if not args.dry_run: request(args, "PUT", "/v1/catalogs/%s/migrations/%d" % (urllib.parse.quote(wid), v), {"name": name, "checksum": checksum}) entry["state"] = "applied_now" report["pending"] = sum(1 for f in report["files"] if f["state"] in ("pending", "repair")) return report # --------------------------------------------------------------------------- lhbox plan | apply (tablemere#3007, PLAN 21) # A repository declares its LakehouseBox setup in lakehouse.yaml; `lhbox plan` says what `lhbox apply` would change, and # `apply` changes it. Declared: a catalog (format version, public, AGENTS.md, table descriptions, its migrations), the # URL prefixes its scheduled SQL may POST to, its connections, its scheduled SQL sinks (the SQL from files). Tables come # only from migrations (`lhbox migrate`): apply runs them first. apply creates and updates; it never deletes unless # --prune is given (and then never a table or a row: sinks, connections and POST prefixes not in the file), and never # publishes or unpublishes a catalog without --publish. Each change goes through the route a person would use, with the # same checks: a sink's query is previewed before it is created or changed. # The file is a subset of YAML (no anchors, tags or multi-line strings): mappings, lists, `{…}` and `[…]` flow # collections, quoted and plain scalars, `#` comments. Anything else is refused with its line. LAKEFILE_VERSION = 1 class _YamlError(ValueError): pass def _yaml_scalar(text, line): t = text.strip() if t == "": return None if t[0] in "'\"": q = t[0] if len(t) < 2 or t[-1] != q: raise _YamlError("line %d: an unclosed %s quote" % (line, "single" if q == "'" else "double")) body = t[1:-1] if q == "'": return body.replace("''", "'") try: return json.loads('"' + body + '"') except ValueError: raise _YamlError("line %d: a double-quoted string with an escape YAML-JSON does not read" % line) if t[0] in "&*!|>%@`": raise _YamlError("line %d: %r is YAML this file format does not take (anchors, tags, block strings)" % (line, t[:20])) low = t.lower() if low in ("true", "yes", "on"): return True if low in ("false", "no", "off"): return False if low in ("null", "~"): return None if re.fullmatch(r"[-+]?\d+", t): return int(t) if re.fullmatch(r"[-+]?\d+\.\d*", t): return float(t) return t def _yaml_strip_comment(text): """The text before a `#` comment (a # inside quotes or a word, as in url#frag, is kept).""" out, q = [], None for i, ch in enumerate(text): if q: if ch == q: q = None elif ch in "'\"": q = ch elif ch == "#" and (i == 0 or text[i - 1].isspace()): break out.append(ch) return "".join(out).rstrip() def _yaml_split_flow(text, line): """The items of a flow collection's inside, split at commas outside (), [], {} and quotes.""" parts, cur, depth, q = [], [], 0, None for ch in text: if q: cur.append(ch) if ch == q: q = None continue if ch in "'\"": q = ch elif ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 if depth < 0: raise _YamlError("line %d: a closing %s with nothing open" % (line, ch)) elif ch == "," and depth == 0: parts.append("".join(cur)) cur = [] continue cur.append(ch) if q or depth: raise _YamlError("line %d: a quote or bracket left open" % line) parts.append("".join(cur)) return parts def _yaml_flow(text, line): """A flow collection {a: b, c: [d]} or [a, b], or a scalar.""" t = text.strip() if t.startswith("{") or t.startswith("["): if not ((t[0] == "{" and t.endswith("}")) or (t[0] == "[" and t.endswith("]"))): raise _YamlError("line %d: a flow collection that does not close on its line" % line) items = [x for x in _yaml_split_flow(t[1:-1], line) if x.strip()] if t[0] == "[": return [_yaml_flow(x, line) for x in items] out = {} for x in items: k, sep, v = x.partition(":") if not sep: raise _YamlError("line %d: %r in a {…} mapping has no key: value" % (line, x.strip())) out[_yaml_scalar(k, line)] = _yaml_flow(v, line) return out return _yaml_scalar(t, line) def _yaml_load(text): lines = [] for n, raw in enumerate(text.splitlines(), 1): if "\t" in raw[:len(raw) - len(raw.lstrip())]: raise _YamlError("line %d: indent with spaces, not tabs" % n) body = _yaml_strip_comment(raw) if body.strip() in ("", "---"): continue lines.append((n, len(body) - len(body.lstrip()), body.strip())) pos = [0] def block(indent): n, ind, text = lines[pos[0]] if text.startswith("- ") or text == "-": out = [] while pos[0] < len(lines) and lines[pos[0]][1] == indent and (lines[pos[0]][2].startswith("- ") or lines[pos[0]][2] == "-"): n, ind, text = lines[pos[0]] pos[0] += 1 item = text[1:].strip() if item == "": out.append(block(lines[pos[0]][1]) if pos[0] < len(lines) and lines[pos[0]][1] > indent else None) elif re.match(r"^[^'\"{\[][^:]*:(\s|$)", item): raise _YamlError("line %d: a mapping inside a list item: write it as {key: value} on one line" % n) else: out.append(_yaml_flow(item, n)) return out out = {} while pos[0] < len(lines) and lines[pos[0]][1] == indent: n, ind, text = lines[pos[0]] m = re.match(r"^((?:'[^']*'|\"[^\"]*\"|[^:'\"{\[][^:]*?)):(?:\s+(.*))?$", text) if not m: raise _YamlError("line %d: expected `key: value`, got %r" % (n, text[:40])) key = _yaml_scalar(m.group(1), n) if key in out: raise _YamlError("line %d: %r appears twice" % (n, key)) pos[0] += 1 rest = m.group(2) if rest is not None and rest.strip() != "": out[key] = _yaml_flow(rest, n) elif pos[0] < len(lines) and lines[pos[0]][1] > indent: out[key] = block(lines[pos[0]][1]) else: out[key] = None return out if not lines: return {} doc = block(lines[0][1]) if pos[0] < len(lines): n, ind, text = lines[pos[0]] raise _YamlError("line %d: indentation that matches nothing above it" % n) return doc def _dur_seconds(v): if isinstance(v, int): return v m = re.fullmatch(r"\s*(\d+)\s*([smhd]?)\s*", str(v or "")) if not m: raise ValueError("a duration is a number with s, m, h or d (15m, 1h), got %r" % v) return int(m.group(1)) * {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2)] SINK_KEYS = {"table", "sql", "every", "offset", "mode", "min_rows", "format_version", "key", "engine", "paused", "replace_existing"} AGENT_KEYS = {"prompt", "model", "schedule", "tz", "reads", "writes", "notify_owner", "run_seconds", "state_keys"} CATALOG_KEYS = {"public", "default_format_version", "agents_md", "table_docs", "migrations", "post_prefixes", "connections", "sinks", "agents"} def _lakefile(path): """(spec, base directory) of a lakehouse.yaml, checked; die_json bad_lakefile with the line on anything off.""" try: with open(path, encoding="utf-8") as fh: spec = _yaml_load(fh.read()) except OSError as exc: die_json("lakefile_unreadable", "Cannot read %s: %s" % (path, exc.strerror or exc), EXIT_USAGE, path=path, remedy="-f names the file (default lakehouse.yaml in this folder).") except _YamlError as exc: die_json("bad_lakefile", "%s: %s" % (path, exc), EXIT_USAGE, path=path) def bad(msg): die_json("bad_lakefile", "%s: %s" % (path, msg), EXIT_USAGE, path=path) if not isinstance(spec, dict) or spec.get("version") != LAKEFILE_VERSION: bad("the file starts with `version: %d`" % LAKEFILE_VERSION) extra = sorted(set(spec) - {"version", "project", "catalogs"}) if extra: bad("unknown key(s) %s (version, project, catalogs)" % ", ".join(map(str, extra))) cats = spec.get("catalogs") if not isinstance(cats, dict) or not cats: bad("`catalogs:` names at least one catalog") for cname, c in cats.items(): c = c or {} cats[cname] = c if not isinstance(c, dict): bad("catalog %s is a mapping" % cname) unknown = sorted(set(c) - CATALOG_KEYS) if unknown: bad("catalog %s: unknown key(s) %s" % (cname, ", ".join(map(str, unknown)))) for k, kind in (("post_prefixes", list), ("connections", dict), ("sinks", dict)): if c.get(k) is not None and not isinstance(c[k], kind): bad("catalog %s: %s is a %s" % (cname, k, "list (- item lines)" if kind is list else "mapping of names")) if any(not isinstance(p, str) or not p.startswith("https://") for p in c.get("post_prefixes") or []): bad("catalog %s: post_prefixes are https:// URL prefixes" % cname) for k in ("agents_md", "table_docs", "migrations"): if c.get(k) is not None and not isinstance(c[k], str): bad("catalog %s: %s is a path" % (cname, k)) for sname, sk in (c.get("sinks") or {}).items(): if not isinstance(sk, dict) or not sk.get("table") or not sk.get("sql") or sk.get("every") is None: bad("sink %s needs table, sql (a file) and every" % sname) if not isinstance(sk["table"], str) or sk["table"].count(".") != 1 or not isinstance(sk["sql"], str): bad("sink %s: table is namespace.table and sql a file path" % sname) if sk.get("engine") is not None: sk["engine"] = str(sk["engine"]) # `engine: 1.5` reads as a number; the API takes "1.5" if sk.get("key") is not None and (not isinstance(sk["key"], list) or not all(isinstance(x, str) for x in sk["key"])): bad("sink %s: key is a list of column names ([id] or [id, ts])" % sname) unknown = sorted(set(sk) - SINK_KEYS) if unknown: bad("sink %s: unknown key(s) %s (%s)" % (sname, ", ".join(map(str, unknown)), ", ".join(sorted(SINK_KEYS)))) try: _dur_seconds(sk["every"]) _dur_seconds(sk.get("offset") or 0) except ValueError as exc: bad("sink %s: %s" % (sname, exc)) if c.get("agents") is not None and not isinstance(c["agents"], dict): bad("catalog %s: agents is a mapping of names" % cname) for an, ag in (c.get("agents") or {}).items(): if not isinstance(ag, dict) or not isinstance(ag.get("prompt"), str): bad("agent %s needs prompt (a file)" % an) unknown = sorted(set(ag) - AGENT_KEYS) if unknown: bad("agent %s: unknown key(s) %s (%s)" % (an, ", ".join(map(str, unknown)), ", ".join(sorted(AGENT_KEYS)))) for k in ("reads", "writes", "state_keys"): if ag.get(k) is not None and (not isinstance(ag[k], list) or not all(isinstance(x, str) for x in ag[k])): bad("agent %s: %s is a list" % (an, k)) if ag.get("tz") and not ag.get("schedule"): bad("agent %s: tz goes with schedule" % an) for cn, cc in (c.get("connections") or {}).items(): if not isinstance(cc, dict) or not (cc.get("integration") or (cc.get("url_prefix") and cc.get("value_env"))): bad("connection %s takes integration (an organisation web key) or url_prefix with kind and value_env " "(the environment variable that holds the value: never the value in the file)" % cn) return spec, os.path.dirname(os.path.abspath(path)) def _read_rel(base, rel, what): p = rel if os.path.isabs(rel) else os.path.join(base, rel) try: with open(p, encoding="utf-8") as fh: return fh.read() except OSError as exc: die_json("lakefile_unreadable", "%s %s: %s" % (what, rel, exc.strerror or exc), EXIT_USAGE, path=p) def _sql_diff(old, new): import difflib return "".join(difflib.unified_diff((old or "").splitlines(True), (new or "").splitlines(True), "live", "file", n=1)) def _get_ok(args, path, ok404=False): """GET's answer; None for a 404 when `ok404` (a feature off, a resource not there yet); any other failure is the API's own envelope and exit code (_fail), as for every command.""" status, parsed = request_status(args, "GET", path) if status == 404 and ok404: return None if status >= 400: _fail("GET", path.split("?")[0], status, parsed, None) return parsed def lake_plan(args, spec, base): """The changes, in the order apply makes them: [{resource, name, action, detail, do}] where `do` is the call apply makes (method, path, body) or a callable; action create|update|delete|publish|blocked|unmanaged|notice.""" changes = [] def add(resource, name, action, detail=None, do=None): changes.append({"resource": resource, "name": name, "action": action, "detail": detail or {}, "do": do}) usage = _get_ok(args, "/v1/usage") or {} # each organisation's scheduled SQL sinks as its limit counts them (every catalog, ones the caller cannot read too) org_count = {o.get("org_id"): o for o in usage.get("organizations") or []} new_sql: dict = {} for cname, c in spec["catalogs"].items(): wh = _get_ok(args, "/v1/catalogs/%s" % urllib.parse.quote(cname), ok404=True) if wh is None: add("catalog", cname, "blocked", {"why": "the catalog does not exist: lhbox catalog create %s, then plan again" % cname}) continue wid = wh.get("warehouse_id") org = org_count.get(wh.get("org_id")) or {} sql_limit = (org.get("limits") or usage.get("limits") or {}).get("sql_sinks") sql_limit = sql_limit.get("limit") if isinstance(sql_limit, dict) else sql_limit org_sql = org.get("sql_sinks") if spec.get("project") and wh.get("project") != spec["project"]: add("catalog", cname, "unmanaged", {"field": "project", "file": spec["project"], "live": wh.get("project"), "why": "a catalog does not move between projects: apply leaves it"}) if c.get("default_format_version") is not None and wh.get("default_format_version") != c["default_format_version"]: add("catalog", cname, "update", {"default_format_version": [wh.get("default_format_version"), c["default_format_version"]]}, ("PATCH", "/v1/warehouses/%s" % wid, {"default_format_version": c["default_format_version"]})) if c.get("agents_md"): text = _read_rel(base, c["agents_md"], "agents_md") cur = (_get_ok(args, "/v1/warehouses/%s/agents-md" % wid, ok404=True) or {}).get("agents_md") or {} sha = hashlib.sha256(text.encode("utf-8")).hexdigest() if cur.get("sha256") != sha: add("agents_md", cname, "update" if cur.get("present") else "create", {"file": c["agents_md"]}, ("PUT", "/v1/warehouses/%s/agents-md" % wid, {"text": text, "base_sha256": cur.get("sha256") if cur.get("present") else None})) if c.get("migrations"): mdir = c["migrations"] if os.path.isabs(c["migrations"]) else os.path.join(base, c["migrations"]) rep = migrate_run(args, wid, mdir, True, False) pend = [f["file"] for f in rep["files"] if f["state"] == "pending"] if pend: add("migrations", cname, "create", {"files": pend, "tables": sum(1 for f in rep["files"] for a in f.get("actions") or [] if a["action"] == "create")}, lambda wid=wid, mdir=mdir: migrate_run(args, wid, mdir, False, False)) for d in rep["differences"]: add("table", d["table"], "notice", {k: v for k, v in d.items() if k != "table" and v}) live_pp = {p["url_prefix"] for p in (_get_ok(args, "/v1/sql/post-prefixes?" + urllib.parse.urlencode( {"warehouse": wid}), ok404=True) or {}).get("post_prefixes") or []} for p in c.get("post_prefixes") or []: if p not in live_pp: add("post_prefix", p, "create", {}, ("POST", "/v1/sql/post-prefixes", {"warehouse": wid, "url_prefix": p})) for p in sorted(live_pp - set(c.get("post_prefixes") or [])): add("post_prefix", p, "delete", {"not_in_file": True}, ("DELETE", "/v1/sql/post-prefixes?" + urllib.parse.urlencode({"warehouse": wid, "url_prefix": p}), None)) conns = {x["name"]: x for x in (_get_ok(args, "/v1/sql/connections?" + urllib.parse.urlencode( {"warehouse": wid}), ok404=True) or {}).get("connections") or []} integ = {i["name"]: i for i in (_get_ok(args, "/v1/integrations", ok404=True) or {}).get("integrations") or []} keyed_hosts = {} # web-key host -> its owner (the key goes to their queries only) unseen_keys = [] # web keys the caller cannot see (a member sees only their own) for cn, cc in (c.get("connections") or {}).items(): if cc.get("integration"): it = integ.get(cc["integration"]) if it and it.get("web_host"): keyed_hosts[it["web_host"]] = (cn, it.get("created_by"), it.get("mine")) elif conns.get(cn, {}).get("url_prefix"): unseen_keys.append((cn, urllib.parse.urlsplit(conns[cn]["url_prefix"]).hostname)) live = conns.get(cn) if live is None: if cc.get("integration"): body = {"warehouse": wid, "name": cn, "integration": cc["integration"]} else: body = {"warehouse": wid, "name": cn, "url_prefix": cc["url_prefix"], "kind": cc.get("kind", "bearer"), "value": "env:" + cc["value_env"]} if cc.get("header_name"): body["header_name"] = cc["header_name"] detail = {k: v for k, v in body.items() if k not in ("warehouse", "value")} if cc.get("value_env"): detail["value_from_env"] = cc["value_env"] # the variable's name; its value only at apply add("connection", cn, "create", detail, ("POST", "/v1/sql/connections", body)) else: it = integ.get(cc.get("integration")) if cc.get("integration") else None differ = {} if cc.get("url_prefix") and live.get("url_prefix") != cc["url_prefix"]: differ["url_prefix"] = [live.get("url_prefix"), cc["url_prefix"]] if cc.get("integration") and it and live.get("integration_id") != it.get("integration_id"): differ["integration"] = [live.get("integration_id"), cc["integration"]] if not cc.get("integration") and live.get("integration_id"): differ["integration"] = [live.get("integration_id"), None] if not cc.get("integration") and cc.get("kind", "bearer") != live.get("kind"): differ["kind"] = [live.get("kind"), cc.get("kind", "bearer")] if not cc.get("integration") and (cc.get("header_name") or None) != (live.get("header_name") or None): differ["header_name"] = [live.get("header_name"), cc.get("header_name")] if differ: add("connection", cn, "unmanaged", dict(differ, why="a connection is changed by deleting it and " "applying again (lhbox sink connection delete)")) for cn in sorted(set(conns) - set(c.get("connections") or {})): add("connection", cn, "delete", {"not_in_file": True}, ("DELETE", "/v1/sql/connections/%s?%s" % (urllib.parse.quote(cn), urllib.parse.urlencode({"warehouse": wid})), None)) live_sinks = {s["name"]: s for s in (_get_ok(args, "/v1/sinks?" + urllib.parse.urlencode( {"warehouse": wid}), ok404=True) or {}).get("sinks") or []} for sn, sk in (c.get("sinks") or {}).items(): sql = _read_rel(base, sk["sql"], "sink %s sql" % sn) every, offset = _dur_seconds(sk["every"]), _dur_seconds(sk.get("offset") or 0) owner = next(((cn, o, mine) for h, (cn, o, mine) in keyed_hosts.items() if h and h in sql), None) live = live_sinks.get(sn) authoring = live is None or sql.strip() != ((live.get("sql") or {}).get("query") or "").strip() # `mine` is the API's word (the person behind the key's creator, as a query's author is resolved); an API # that does not say it leaves the question to the preview if authoring and owner and owner[2] is False: add("sink", sn, "blocked", {"why": "its query uses connection %s, an organisation web key of another person " "(%s): the key goes only into its owner's queries, so its preview would " "answer 401. Have its owner run apply." % owner[:2]}) continue if authoring and owner and owner[2] is None: add("sink", sn, "notice", {"why": "its query uses connection %s, a web key of %s: only its owner's queries " "get it (the preview decides)" % owner[:2]}) unseen = next((cn for cn, h in unseen_keys if h and h in sql), None) if authoring and unseen: add("sink", sn, "notice", {"why": "its query uses connection %s, an organisation web key you cannot see: " "only its owner's queries get it (the preview decides)" % unseen}) if live is None: body = {"name": sn, "warehouse": wid, "table": sk["table"], "sql": sql, "every": every, "offset": offset} for k in ("mode", "min_rows", "key", "engine", "paused", "replace_existing"): if sk.get(k) is not None: body[k] = sk[k] ns, tname = sk["table"].split(".", 1) def table_missing(wid=wid, ns=ns, tname=tname): return _get_ok(args, "/v1/table?" + urllib.parse.urlencode( {"warehouse": wid, "namespace": ns, "name": tname}), ok404=True) is None def create_sink(body=body, table_missing=table_missing, fv=sk.get("format_version")): # whether the sink makes its table is decided now, not at plan time: this run's migrations may have # made it since (a create_table + format_version for a table that exists is refused, 409) b = dict(body) if table_missing(): b["create_table"] = True if fv: b["format_version"] = fv return request(args, "POST", "/v1/sinks", b) body["create_table"] = table_missing() k = wh.get("org_id") new_sql[k] = new_sql.get(k, 0) + 1 if sql_limit is not None and org_sql is not None and org_sql + new_sql[k] > int(sql_limit): add("sink", sn, "blocked", {"why": "the organisation has %d scheduled SQL sinks, its limit is %s: this " "one would be refused (limit_exceeded)" % (org_sql + new_sql[k] - 1, sql_limit)}) new_sql[k] -= 1 continue add("sink", sn, "create", {"table": sk["table"], "every": every, "offset": offset, "create_table": bool(body.pop("create_table")), "mode": sk.get("mode")}, create_sink) continue q = live.get("sql") or {} if live.get("table") != sk["table"]: add("sink", sn, "unmanaged", {"table": [live.get("table"), sk["table"]], "why": "a sink's table is chosen when it is made: delete it and apply again"}) continue if sk.get("mode") and (q.get("mode") or "append") != sk["mode"]: add("sink", sn, "unmanaged", {"mode": [q.get("mode"), sk["mode"]], "why": "a sink's mode is chosen when it is made: delete it and apply again"}) continue patch, detail = {}, {} if sql.strip() != (q.get("query") or "").strip(): patch["sql"], detail["sql_diff"] = sql, _sql_diff(q.get("query"), sql) if q.get("every_seconds") != every: patch["every"], detail["every"] = every, [q.get("every_seconds"), every] if (q.get("offset_seconds") or 0) != offset: patch["offset"], detail["offset"] = offset, [q.get("offset_seconds"), offset] if sk.get("min_rows") is not None and q.get("min_rows") != sk["min_rows"]: patch["min_rows"], detail["min_rows"] = sk["min_rows"], [q.get("min_rows"), sk["min_rows"]] if sk.get("engine") and q.get("engine") != str(sk["engine"]): patch["engine"], detail["engine"] = str(sk["engine"]), [q.get("engine"), str(sk["engine"])] if sk.get("key") is not None and (live.get("key") or None) != (sk["key"] or None): patch["key"], detail["key"] = sk["key"], [live.get("key"), sk["key"]] if sk.get("paused") is not None and bool(q.get("paused")) != bool(sk["paused"]): patch["paused"], detail["paused"] = bool(sk["paused"]), [q.get("paused"), bool(sk["paused"])] if patch: add("sink", sn, "update", detail, ("PATCH", "/v1/sinks/%s" % live["sink_id"], patch)) for sn in sorted(n for n, s in live_sinks.items() if n not in (c.get("sinks") or {}) and s.get("kind") == "sql"): add("sink", sn, "delete", {"not_in_file": True, "table": live_sinks[sn].get("table"), "note": "the sink only: its table and rows stay"}, ("DELETE", "/v1/sinks/%s" % live_sinks[sn]["sink_id"], None)) if c.get("table_docs"): try: docs = json.loads(_read_rel(base, c["table_docs"], "table_docs")) except ValueError as exc: die_json("bad_lakefile", "table_docs %s is not JSON: %s" % (c["table_docs"], exc), EXIT_USAGE) if not isinstance(docs, dict) or any(not isinstance(k, str) or k.count(".") != 1 or not isinstance(v, dict) for k, v in docs.items()): die_json("bad_lakefile", "table_docs %s maps \"namespace.table\" to {\"doc\": ..., \"columns\": {...}}" % c["table_docs"], EXIT_USAGE) for tref, d in docs.items(): ns, tname = tref.split(".", 1) st, t = request_status(args, "GET", "/v1/table?" + urllib.parse.urlencode( {"warehouse": wid, "namespace": ns, "name": tname})) if st != 200: add("table_docs", tref, "notice", {"why": "the table does not exist yet (its migration makes it)"}) continue have = {x.get("name"): x.get("doc") or None for x in t.get("schema") or []} body = {"catalog_id": wid, "namespace": ns, "name": tname} if d.get("doc") is not None and (t.get("doc") or None) != d["doc"]: body["doc"] = d["doc"] cols = {k: v for k, v in (d.get("columns") or {}).items() if k in have and have[k] != v} if cols: body["column_docs"] = cols if len(body) > 3: add("table_docs", tref, "update", {"table_doc": "doc" in body, "columns": len(cols)}, ("PATCH", "/v1/table", body)) if c.get("agents"): # hosted agents (#3031): the organisation's, made and changed through /v1/agents with its own rules (an agent # that uses a person's integrations is changed by that person only: the API's refusal is relayed); never # deleted by apply, --prune included (an agent is the organisation's, not this catalog's) org_q = ("?" + urllib.parse.urlencode({"org_id": wh["org_id"]})) if wh.get("org_id") else "" live_agents = {x.get("name"): x for x in (_get_ok(args, "/v1/agents" + org_q, ok404=True) or {}).get("agents") or []} for an, ag in c["agents"].items(): prompt = _read_rel(base, ag["prompt"], "agent %s prompt" % an) want = {"prompt": prompt, "read": sorted(ag.get("reads") or [cname]), "write": sorted(ag.get("writes") or [])} if ag.get("model"): want["model"] = ag["model"] if ag.get("schedule"): cron = ag["schedule"] # as the API stores it (agents._valid_schedule), so a plan settles want["schedule"] = {"cron": " ".join(cron.split()) if isinstance(cron, str) else cron, "tz": ag.get("tz") or "UTC"} for k in ("notify_owner", "run_seconds", "state_keys"): if ag.get(k) is not None: want[k] = ag[k] if isinstance(want.get("state_keys"), list) and all(isinstance(x, str) for x in want["state_keys"]): want["state_keys"] = sorted(set(want["state_keys"])) # the API keeps sorted(set(keys)) missing = [] for w in want["write"]: parts = w.split(".") if len(parts) == 3 and parts[0] == cname and _get_ok(args, "/v1/table?" + urllib.parse.urlencode( {"warehouse": wid, "namespace": parts[1], "name": parts[2]}), ok404=True) is None: missing.append(w) if missing: # apply plans again after this run's migrations: an agent whose table a pending migration makes is # created then; one whose table no migration makes stays blocked add("agent", an, "blocked", {"why": "it writes %s, which does not exist: a migration makes it (apply " "creates the agent once it does)" % ", ".join(missing)}) continue live = live_agents.get(an) if live is None: body = dict(want, name=an, **({"org_id": wh["org_id"]} if wh.get("org_id") else {})) add("agent", an, "create", {k: v for k, v in want.items() if k != "prompt"}, ("POST", "/v1/agents", body)) continue cur = {"prompt": live.get("prompt") or "", "read": sorted(live.get("read") or []), "write": sorted(live.get("write") or []), "model": live.get("model"), "schedule": live.get("schedule"), "notify_owner": live.get("notify_owner"), "run_seconds": live.get("run_seconds"), "state_keys": live.get("state_keys")} patch, detail = {}, {} for k, v in want.items(): have = cur.get(k) if k == "prompt": if (have or "").strip() != v.strip(): patch[k], detail["prompt_diff"] = v, _sql_diff(have, v) elif k == "schedule": if not have or have.get("cron") != v["cron"] or (have.get("tz") or "UTC") != v["tz"]: patch[k], detail[k] = v, [have, v] elif have != v: patch[k], detail[k] = v, [have, v] if patch: add("agent", an, "update", detail, ("PATCH", "/v1/agents/%s" % urllib.parse.quote(live.get("agent_id") or an), patch)) if c.get("public") is not None and bool(wh.get("public")) != bool(c["public"]): if c["public"]: add("catalog", cname, "publish", {"public": [bool(wh.get("public")), True], "note": "every data file becomes readable by anyone"}, ("POST", "/v1/warehouses/%s/public" % wid, {"confirm": cname})) else: add("catalog", cname, "publish", {"public": [True, False]}, ("DELETE", "/v1/warehouses/%s/public?%s" % (wid, urllib.parse.urlencode({"confirm": cname})), None)) return changes _PLAN_MARK = {"create": "+", "update": "~", "delete": "-", "publish": "!", "blocked": "x", "unmanaged": "?", "notice": "i"} def _plan_view(changes): return [{k: v for k, v in c.items() if k != "do"} for c in changes] def _plan_drift(args, changes): """For each sink the plan would update: who changed it since the last `lhbox apply`, from the object history (GET /v1/changes). `apply` makes the live sink match the file, so it overwrites that change; the plan names it first (there is no --force: the plan is the warning, and the overwritten version stays in history, restorable). Adds `drift` {change_id, change_time, actor_kind, actor_id, via, reason} to the change; nothing when the history is not there (an older server) or holds no change but apply's own.""" for c in changes: if c["action"] != "update" or c["resource"] != "sink" or not isinstance(c.get("do"), tuple): continue sink_id = c["do"][1].rsplit("/", 1)[-1] # advisory: a history that does not answer (busy, an older server) never stops a plan or an apply status, out = request_status(args, "GET", "/v1/changes?" + urllib.parse.urlencode({"object": sink_id, "limit": "100"})) rows = (out.get("changes") or []) if status == 200 and isinstance(out, dict) else [] # newest first since = [] for r in rows: if r.get("via") == "apply": break # everything older was already the file's if r.get("reason_code") != "baseline": since.append(r) if since: r = since[0] c["drift"] = {"change_id": r.get("change_id"), "change_time": r.get("change_time"), "actor_kind": r.get("actor_kind"), "actor_id": r.get("actor_id"), "via": r.get("via"), "reason": r.get("reason") or r.get("reason_code"), "changes_since_apply": len(since)} return changes def _drift_line(d): """The warning under a sink the plan would overwrite. Every part is the server's, and the reason is another person's free text: shown through _visible, so an escape sequence in it cannot erase or forge a plan line (#2930).""" who = "%s %s" % (d.get("actor_kind"), (d.get("actor_id") or "")[:8]) if d.get("actor_id") else str(d.get("actor_kind")) more = " (and %d earlier)" % (d["changes_since_apply"] - 1) if (d.get("changes_since_apply") or 1) > 1 else "" return "changed by %s at %s via %s%s%s; apply will put back the file's version (lhbox history --change %s)" % ( _visible(who), _visible(str(d.get("change_time") or "")[:16].replace("T", " ")), _visible(d.get("via")), " (%s)" % _visible(d["reason"]) if d.get("reason") else "", more, _visible(d.get("change_id"))) def _print_plan(changes, prune, publish): for c in changes: d = dict(c["detail"]) diff = d.pop("sql_diff", None) or d.pop("prompt_diff", None) extra = "" if c["action"] == "delete" and not prune: extra = " (not in the file: kept; --prune deletes it)" if c["action"] == "publish" and not publish: extra = " (needs --publish)" print("%s %-11s %-34s %s%s" % (_PLAN_MARK.get(c["action"], " "), c["resource"], c["name"], json.dumps(d, ensure_ascii=False) if d else "", extra)) if c.get("drift"): print(" ! " + _drift_line(c["drift"])) if diff: for ln in diff.splitlines(): print(" " + ln) def _plan_counts(changes, prune, publish): act = [c for c in changes if c["action"] in ("create", "update") or (c["action"] == "delete" and prune) or (c["action"] == "publish" and publish)] return {"to_apply": len(act), "kept_not_in_file": sum(1 for c in changes if c["action"] == "delete" and not prune), "blocked": sum(1 for c in changes if c["action"] == "blocked"), "needs_publish": sum(1 for c in changes if c["action"] == "publish" and not publish), "unmanaged": sum(1 for c in changes if c["action"] == "unmanaged")} def _last_commit_subject(path): """The subject of the last commit that touched the folder of the file `path`, when that commit IS what is being applied: the file is tracked and nothing in its folder (the file, its .sql files) differs from the commit. None otherwise (no git, not tracked, uncommitted edits): an unrelated commit's subject is not why this run changes anything, and `apply` then asks for a reason.""" directory, name = os.path.dirname(os.path.abspath(path)), os.path.basename(path) def git(*a): try: out = subprocess.run(["git", "-C", directory, *a], capture_output=True, text=True, timeout=10) except (OSError, subprocess.SubprocessError): return None return out.stdout if out.returncode == 0 else None if git("ls-files", "--error-unmatch", "--", name) is None: return None dirty = git("status", "--porcelain", "--", ".") if dirty is None or dirty.strip(): return None return (git("log", "-1", "--pretty=%s", "--", ".") or "").strip()[:500] or None def cmd_plan(args): spec, base = _lakefile(args.file) changes = _plan_drift(args, lake_plan(args, spec, base)) counts = _plan_counts(changes, False, False) if _want_json(args): print_json({"file": args.file, "changes": _plan_view(changes), **counts}) return _print_plan(changes, False, False) print("plan: %(to_apply)d to apply, %(blocked)d blocked, %(needs_publish)d needing --publish, %(kept_not_in_file)d " "not in the file (kept; --prune deletes)." % counts, file=sys.stderr) def cmd_apply(args): spec, base = _lakefile(args.file) changes = _plan_drift(args, lake_plan(args, spec, base)) counts = _plan_counts(changes, args.prune, args.publish) todo = [c for c in changes if c["action"] in ("create", "update") or (c["action"] == "delete" and args.prune) or (c["action"] == "publish" and args.publish)] if not _want_json(args): _print_plan(changes, args.prune, args.publish) # deletes first (a rename under --prune: the old prefix or table holder goes before the new one asks for it), the # publishing last; and what can be checked here is checked before anything is sent todo = ([c for c in todo if c["action"] == "delete"] + [c for c in todo if c["action"] in ("create", "update")] + [c for c in todo if c["action"] == "publish"]) for c in todo: body = c["do"][2] if isinstance(c["do"], tuple) else None if body and isinstance(body.get("value"), str) and body["value"].startswith("env:") and not os.environ.get(body["value"][4:]): die_json("missing_value", "connection %s: the environment variable %s is empty; nothing was changed." % (c["name"], body["value"][4:]), EXIT_USAGE, connection=c["name"]) deletes = [c for c in todo if c["action"] in ("delete", "publish")] if deletes and not args.yes: if not sys.stdin.isatty(): die_json("confirmation_needed", "%d change(s) delete or publish (%s); pass --yes to make them." % ( len(deletes), ", ".join("%s %s" % (c["resource"], c["name"]) for c in deletes)), EXIT_USAGE, changes=_plan_view(deletes)) if input("Delete or publish %d thing(s) listed above? Type yes: " % len(deletes)).strip() != "yes": die("Nothing was changed.", EXIT_USAGE) done = [] if todo: # every change of this run is one operation in the object history, with why: -m, else --reason, else the last # commit's subject (the file is the repository's: its commit says why it changed) why = getattr(args, "message", None) or getattr(args, "reason", None) or os.environ.get("LHBOX_REASON") \ or _last_commit_subject(args.file) if not why: die_json("reason_required", "Say why: lhbox apply -m \"\" (kept with every change in " "the object history). Inside a git repository the last commit's subject is used.", EXIT_USAGE) args.reason = why args._operation = "apply-" + uuid.uuid4().hex[:16] _apply_changes(args, todo, done) if any(c["resource"] == "migrations" for c in todo): # tables the migrations just made: what refers to them (their descriptions, a sink's create_table) is planned # again now that they exist, and applied in the same run again = [c for c in lake_plan(args, spec, base) if c["action"] in ("create", "update")] _apply_changes(args, again, done) changes = changes + [c for c in again if c not in changes] out = {"file": args.file, "applied": done, **counts, "not_applied": _plan_view([c for c in changes if c not in todo and c["action"] not in ("notice", "create", "update")])} if _want_json(args): print_json(out) return print("apply: %d change(s) made; %d blocked, %d needing --publish, %d not in the file (kept)." % ( len(done), counts["blocked"], counts["needs_publish"], counts["kept_not_in_file"]), file=sys.stderr) def _apply_changes(args, todo, done): for c in todo: if callable(c["do"]): result = c["do"]() else: method, path, body = c["do"] if body and isinstance(body.get("value"), str) and body["value"].startswith("env:"): var = body["value"][4:] if not os.environ.get(var): die_json("missing_value", "connection %s: the environment variable %s is empty." % (c["name"], var), EXIT_USAGE, connection=c["name"]) body = dict(body, value=os.environ[var]) result = request(args, method, path, body) done.append({"resource": c["resource"], "name": c["name"], "action": c["action"], **({"sink_id": result.get("sink_id")} if isinstance(result, dict) and result.get("sink_id") else {})}) if not _want_json(args): print("done: %s %s %s" % (c["action"], c["resource"], c["name"]), file=sys.stderr) def cmd_table_document(args): """PATCH /v1/table with doc / column_docs: the table's description and its columns', in one commit. --from FILE takes JSON {"doc": "...", "columns": {"name": "..."}}; --doc and --column add to or override it.""" body_doc, cols = _MISSING_DOC, {} if args.from_file: try: fh = sys.stdin if args.from_file == "-" else open(os.path.expanduser(args.from_file)) except OSError as exc: die_json("docs_file_unreadable", "Cannot read --from %s: %s" % (args.from_file, exc.strerror or exc), EXIT_USAGE, path=args.from_file, remedy='Point --from at a readable JSON file {"doc": "...", "columns": {"name": "..."}}, or - for stdin.') with fh: try: spec = json.load(fh) except ValueError as exc: die_json("bad_docs_file", "--from wants JSON: {\"doc\": \"...\", \"columns\": {\"name\": \"...\"}} (%s)" % exc, EXIT_USAGE) if not isinstance(spec, dict) or not isinstance(spec.get("columns", {}), dict): die_json("bad_docs_file", "--from wants a JSON object with doc and/or columns {name: text}.", EXIT_USAGE) body_doc, cols = spec.get("doc", _MISSING_DOC), dict(spec.get("columns") or {}) # "doc": null removes it for spec in args.column or []: k, sep, v = spec.partition("=") if not sep or not k.strip() or not v.strip(): die_json("bad_column", "--column wants name=description, got %r" % spec, EXIT_USAGE, remedy='--column ts="When the reading was taken (UTC)" (repeatable)') cols[k.strip()] = v if args.doc is not None: body_doc = args.doc ns, name = _table_ref(args) body = {"catalog_id": _table_catalog(args, "table document"), "namespace": ns, "name": name} if body_doc is not _MISSING_DOC: body["doc"] = body_doc if cols: body["column_docs"] = cols if "doc" not in body and not cols: die_json("nothing_to_change", "Give --doc, --column name=text and/or --from FILE.", EXIT_USAGE) out = request(args, "PATCH", "/v1/table", body) if _want_json(args): print_json(out) return print("Table %s described: %s%d column(s)." % (out.get("table"), "the table and " if "doc" in body else "", len(out.get("columns_described") or []))) VENDED_SECRET_KEYS = ("s3.secret-access-key", "s3.session-token") VENDED_MASKED_NOTE = ("the secret key and the session token are shown as ******** (the key id is not secret): " "--show-secrets prints them, for a boto3 or aws-cli session that reads the table's files") def cmd_credentials(args): ns, name = _table_ref(args) body = {"catalog_id": _table_catalog(args, "credentials"), "namespace": ns, "name": name} if getattr(args, "expires", None) is not None: body["expires"] = args.expires out = request(args, "POST", "/v1/credentials", body) storage = out.get("storage") if isinstance(out, dict) else None if not getattr(args, "show_secrets", False) and isinstance(storage, dict): # masked like `connect` and `catalog rotate` (#1755: an agent exploring the CLI printed a live session into its # transcript); wherever the answer repeats them, the one masking rule secrets = [storage.get(k) for k in VENDED_SECRET_KEYS if storage.get(k)] if secrets: out = dict(mask_secrets(out, secrets), secrets_masked=True, secrets_note=VENDED_MASKED_NOTE) emit(args, out) def cmd_connect(args): ref = catalog_arg(args) or "" if "/" in ref: # /: another organisation's PUBLIC catalog (research/38) if getattr(args, "edge", False): die_json("edge_reads_public", "--edge is for your own catalogs: a public catalog is already read through the CDN.", EXIT_USAGE, remedy="lhbox connect --catalog %s (without --edge)" % ref) if args.engine != "duckdb": die_json("public_catalog_engine", "A public catalog's recipe is for DuckDB; --engine %s is not offered for it." % args.engine, EXIT_USAGE, remedy="lhbox connect --catalog %s (DuckDB), or lhbox duckdb --catalog %s" % (ref, ref)) if getattr(args, "write", False): die_json("public_catalog_read_only", "%s is a public catalog: it has a read-only recipe, never a writing one." % ref, EXIT_USAGE, remedy="lhbox connect --catalog %s (without --write)" % ref) pub = public_catalog_rec(args, ref) if _want_json(args): print_json(pub["json"]) return print("-- %s: read-only, the catalog's shared public-reader key (it reads this catalog's tables and nothing else)" % ref) for note in pub.get("notes", []): print("-- note: " + note) print(pub["sql"]) return params = {"catalog_id": resolve_catalog(args), "engine": args.engine} if getattr(args, "edge", False): if getattr(args, "write", False): die_json("edge_reads_read_only", "--edge is a read recipe: it cannot be --write.", EXIT_USAGE, remedy="lhbox connect --edge (reads through the CDN), or --write without --edge") params.update(level="read", edge="true") # Edge reads (docs/edge-reads.md): DuckDB's read recipe via the CDN elif getattr(args, "readonly", False): # the catalog's read-only recipe whatever you hold (GET /v1/connection?level=read): the one to hand a colleague, # or to attach in a session that must not write (the account page's Catalog explorer attaches this way) params["level"] = "read" elif getattr(args, "write", False): # the writing recipe, asked for explicitly (GET /v1/connection?level=write): Snowflake's is read-only unless asked, # since its external volume keeps a static key pair (research/55 §4b); a read holder is refused, never downgraded params["level"] = "write" q = urllib.parse.urlencode(params) if getattr(args, "catalog_token", False) and args.engine not in ("duckdb", "pyiceberg"): die_json("catalog_token_engine", "A catalog token's samples are for DuckDB and PyIceberg; --engine %s has none." % args.engine, EXIT_USAGE, remedy="lhbox connect --catalog-token --engine duckdb (or pyiceberg)") out = request(args, "GET", "/v1/connection?" + q) if args.engine in ("duckdb", "pyiceberg") and (getattr(args, "catalog_token", False) or ( out.get("credentials") == "vended_only" and wants_catalog_token(out))): # namespace or table grants with no key pair (a service account), or asked for: the catalog token and its samples return _connect_catalog_token(args, out) if out.get("credentials") == "vended_only": # no key pair to paste (a service account, an application connection): the answer as it is, and what works if _want_json(args): print_json(out) else: print("-- %s: no static catalog key for this identity (level %s). %s" % (out.get("catalog_alias") or "catalog", out.get("level"), out.get("note") or "")) print("-- " + VENDED_ONLY_REMEDY) return if not getattr(args, "show_secrets", False): # the catalog credential's secret is masked wherever the recipe repeats it (the credential, the one-string form, # sql, conf, code): 2026-09-28 a user's redaction masked `sql` and still leaked the other two. The key id stays. out = masked_recipe(out) if args.engine == "duckdb" and not getattr(args, "no_version_check", False): # the recipe is about to be pasted into DuckDB: say now if the DuckDB here is one that writes # manifests the catalog's maintenance cannot read (item 2, platform/docs/duckdb-maintenance-gap.md) warning = duckdb_version_warning(duckdb_versions()) if warning: print(warning, file=sys.stderr) if _want_json(args): print_json(out) return # For a human, the recipe itself is the useful part -- print it ready to paste: SQL comments before SQL (DuckDB # rejects a `#` line, 2026-09-21), `#` before python or conf c = "--" if "sql" in out else "#" print("%s %s -> %s (catalog storage %s)" % (c, args.engine, out["catalog_uri"], out["warehouse"])) if out.get("secrets_masked"): print("%s note: %s" % (c, SECRETS_MASKED_NOTE)) for note in out.get("notes", []): print("%s note: %s" % (c, note)) if out.get("uploaders_note"): print("%s note: %s" % (c, out["uploaders_note"])) if out.get("sinks_note"): print("%s note: %s" % (c, out["sinks_note"])) for n in out.get("namespaces") or []: print("%s namespace %s (%s): %s" % (c, n.get("namespace"), n.get("level"), ", ".join(n.get("tables") or []) or "no tables yet")) for t in out.get("tables") or []: # table grants: these tables only, reached by name (research/45 §2: neither the namespace nor its tables list) print("%s table %s.%s (%s)" % (c, t.get("namespace"), t.get("table"), t.get("level"))) env = out.get("credential_env") or {} if "python" in out and env.get("client_id"): # the code reads the pair from the environment: say what to set (masked unless --show-secrets) cred = out.get("catalog_credential") or {} print("# export %s=%s %s=%s" % (env["client_id"], cred.get("client_id", ""), env["client_secret"], cred.get("client_secret", ""))) for key in ("sql", "python"): if key in out: print(out[key]) if "conf" in out: for k, v in out["conf"].items(): print("%s=%s" % (k, v)) if "properties" in out: # Trino: the catalog properties file, ready to save under the name it says print("# %s" % out.get("properties_file", "etc/catalog/.properties")) print(out["properties"]) def _connect_catalog_token(args, rec): """`lhbox connect` on a catalog token (POST /v1/catalog-token): the bearer of about an hour, masked unless --show-secrets, and the route's sample for the engine, which reads it from the variable the answer names.""" ans = mint_catalog_token(args, rec.get("warehouse_id")) f = _checked_catalog_token(ans) # --readonly / --write: the token's level is the grants' (one identity), so ask for what it is or nothing (high review # of #1488, 1: never a write-capable bearer to a caller who asked for read) level = ans.get("level") if getattr(args, "readonly", False) and level != "read": die_json("read_recipe_unavailable", "You hold write on a namespace or table of this catalog, and a catalog token " "carries your grants as they are: there is no read-only token of it.", EXIT_LIMIT, level=level, remedy="Leave --readonly out for your own token (it writes where you hold write).") if getattr(args, "write", False) and level != "write": die_json("write_level_required", "Your grants on this catalog are read: the catalog token cannot write.", EXIT_AUTH, level=level, remedy="Ask an admin for a write grant on the namespace or table.") if args.engine == "duckdb" and not getattr(args, "no_version_check", False): warning = duckdb_version_warning(duckdb_versions()) if warning: print(warning, file=sys.stderr) show = getattr(args, "show_secrets", False) shown = ans if show else masked_catalog_token(ans) if _want_json(args): print_json(shown) return eng = (ans.get("engines") or {}).get(args.engine) or {} c = "--" if args.engine == "duckdb" else "#" print("%s %s -> %s with a catalog token (level %s via %s, expires %s): the catalog vends each table's storage session" % (c, args.engine, f["uri"], ans.get("level"), ans.get("level_via"), ans.get("expires_at"))) for n in ans.get("namespaces") or []: print("%s namespace %s (%s): %s" % (c, n.get("namespace"), n.get("level"), ", ".join(n.get("tables") or []) or "no tables yet")) for t in ans.get("tables") or []: print("%s table %s.%s (%s)" % (c, t.get("namespace"), t.get("table"), t.get("level"))) if f["env"]: print("%s export %s=%s" % (c, f["env"], f["token"] if show else "********")) if not show: print("%s note: %s" % (c, shown["secrets_note"])) print("%s note: the token is not renewed: ask again before it expires (lhbox duckdb renews it itself)" % c) for note in eng.get("notes") or []: print("%s note: %s" % (c, note)) sample = eng.get("sql") if args.engine == "duckdb" else eng.get("python") if sample and args.engine == "duckdb" and show and f["env"]: # `lhbox connect --show-secrets --human | duckdb` (the documented pipe, high review of #1488, 3): the token is in no # environment there, so the sample's getenv() becomes the literal -- only when the secret was asked for sample = sample.replace("getenv(%s)" % sql_str(f["env"]), sql_str(f["token"])) if sample: print(sample) # ---------------------------------------------------------------- the DuckDB on this machine # platform/docs/duckdb-maintenance-gap.md: DuckDB before 1.5.5 writes manifest lists as nullable Avro unions, # which the catalog's maintenance reader cannot resolve, so tables it writes are never compacted or expired # (Homebrew shipped 1.5.3 on 2026-09-20). Reads are unaffected; writes need 1.5.5 or newer. DUCKDB_MIN = (1, 5, 5) # below this the interactive shell is refused, not warned about: no CREATE SECRET, no Iceberg attach (lhbox duckdb) DUCKDB_SHELL_FLOOR = (1, 0, 0) # DuckDB 2.0's iceberg extension renamed the ATTACH option ENDPOINT to URI: 2.0 still takes ENDPOINT but its shell prints a # deprecation WARNING on stdout, ahead of the query's own output (the nightly's `lhbox duckdb -c` of 2026-10-22, #1738); # 1.5.5 refuses URI ("No 'endpoint' was given to attach"). The CLI names the option the DuckDB it drives expects. DUCKDB_ATTACH_URI = (2, 0, 0) def attach_uri_option(version): """'URI' for a DuckDB 2.0 or newer, 'ENDPOINT' below it or when the version is unknown (ENDPOINT works on both).""" return "URI" if version and tuple(version) >= DUCKDB_ATTACH_URI else "ENDPOINT" def _parse_version(text): """'v1.5.3 (Variegata) 14eca11bd9' or '1.5.5' -> (1, 5, 3); None when there is no version in the text.""" m = re.search(r"v?(\d+)\.(\d+)\.(\d+)", text or "") return tuple(int(x) for x in m.groups()) if m else None def _version_of(argv): """Run a version command (a few seconds at most) -> (version tuple or None, first line of output).""" try: r = subprocess.run(argv, capture_output=True, text=True, timeout=30) except (OSError, subprocess.SubprocessError): return None, "" text = ((r.stdout or "") + (r.stderr or "")).strip().splitlines() first = text[0] if text else "" return (_parse_version(first) if r.returncode == 0 else None), first def _agent_python(): """The interpreter running this CLI (sys.executable): when lhbox was installed into the agent's own environment (pip, a venv), this is the python whose `import duckdb` the agent's code uses -- the third simulated user's check inspected the Homebrew python instead (STATE.md 2026-09-21). A seam: tests replace it.""" return sys.executable _PY_DUCKDB_PROBE = "import sys, duckdb; print(duckdb.__version__); print(sys.executable); print(sys.prefix)" def _python_duckdb(py): """Ask the interpreter at `py` (the path as given, never realpath()'d) for its duckdb version, and for its OWN sys.executable and sys.prefix, from inside the child -> (version or None, raw, executable, prefix or None). A venv's bin/python is a symlink to the base interpreter: realpath() makes the venv, the base and every other venv one binary, while each has its own site-packages (2026-09-28: an activated venv's python3 was dropped as "the same interpreter" as the Homebrew python running lhbox, and only Homebrew's DuckDB was reported). sys.prefix is what tells two environments apart; sys.executable is what the child says it is. An interpreter that prints only a version (older fakes) is reported under the path as given.""" try: r = subprocess.run([py, "-c", _PY_DUCKDB_PROBE], capture_output=True, text=True, timeout=30) except (OSError, subprocess.SubprocessError): return None, "", py, None lines = (r.stdout or "").strip().splitlines() if r.returncode != 0 or not lines: err = ((r.stderr or "") + (r.stdout or "")).strip().splitlines() return None, (err[0] if err else ""), py, None exe = lines[1].strip() if len(lines) > 1 and lines[1].strip() else py prefix = lines[2].strip() if len(lines) > 2 and lines[2].strip() else None return _parse_version(lines[0]), lines[0], exe, prefix def _environment_key(py): """Which environment an interpreter path runs, decided the way Python decides it, without starting it: a venv is the directory above bin/ holding pyvenv.cfg (the path as given, never realpath()'d: the venv's python is a symlink to its base); anything else is its resolved binary. Two names for one environment share the key.""" path = os.path.abspath(os.path.expanduser(py)) root = os.path.dirname(os.path.dirname(path)) if os.path.isfile(os.path.join(root, "pyvenv.cfg")): return ("venv", root) return ("base", os.path.realpath(path)) def duckdb_versions(): """[(where, version, raw)] for every DuckDB reachable from here, in the order an agent meets them: LHBOX_PYTHON (the environment the agent said it uses), the python module of the interpreter running this CLI, then of `python3` on PATH, then the `duckdb` binary on PATH. `where` reads "python module via " / "duckdb binary via ". One environment counts once (_environment_key, before anything is started: `connect` runs this every time); two venvs on one base interpreter are two. Nothing -> [].""" found = [] seen = set() for py in (_env("PYTHON"), _agent_python(), shutil.which("python3")): if not py: continue key = _environment_key(py) if key in seen: # the same environment under two names counts once, and is not started twice continue seen.add(key) v, raw, exe, _prefix = _python_duckdb(py) if v: found.append(("python module via " + exe, v, raw)) exe = shutil.which("duckdb") if exe: v, raw = _version_of([exe, "--version"]) if v: found.append(("duckdb binary via " + exe, v, raw)) return found def _dotted(v): return ".".join(str(x) for x in v) def _via(where): return where.split(" via ", 1)[-1] def _kind(where): return where.split(" via ", 1)[0] def _say_version(where, v): """'1.5.5 via /usr/bin/python3 (python module)'.""" return "%s via %s (%s)" % (_dotted(v), _via(where), _kind(where)) def _upgrade_hint(where): """The command that upgrades THAT DuckDB: the interpreter's own pip for a module, brew for the binary.""" if _kind(where) == "duckdb binary": return "brew upgrade duckdb (or reinstall the duckdb binary from duckdb.org)" return "%s -m pip install -U 'duckdb>=%s'" % (_via(where), _dotted(DUCKDB_MIN)) def duckdb_version_warning(found): """One line naming every DuckDB below the floor, why it matters, and the command that upgrades each; None when all are fine or none exist.""" old = [(where, v) for where, v, _ in found if v < DUCKDB_MIN] if not old: return None return ("warning: DuckDB %s is older than %s: it writes manifest lists the catalog's maintenance cannot read, so " "tables it writes are never compacted or expired until our worker runs on them (reads are fine). Upgrade before " "writing: %s. --no-version-check silences this." % (", ".join(_say_version(where, v) for where, v in old), _dotted(DUCKDB_MIN), "; ".join(_upgrade_hint(where) for where, _ in old))) # ---------------------------------------------------------------- table import, duckdb: the DuckDB on this machine, driven by the CLI # The founder's agent run (STATE.md 2026-09-20, 20:30 UTC): 44 Parquet files imported one statement at a time # were 44 commits and 44 waits; `table import` is ONE statement over the whole file list, so one commit. The # CLI stays stdlib-only: DuckDB is found at run time (the python module when importable, else the binary on # PATH) and the SQL is the same either way. The credential travels recipe -> DuckDB and is never printed. REMOTE_SCHEMES = ("s3://", "s3a://", "gs://", "gcs://", "az://", "abfss://", "https://", "http://", "hf://") def expand_sources(specs): """Local globs expanded here (`glob.glob`, `**` allowed), remote URLs passed through for DuckDB's httpfs to read -> (files in order without duplicates, the specs that matched nothing).""" files, missing, seen = [], [], set() for spec in specs: if spec.startswith(REMOTE_SCHEMES): hits = [spec] else: path = os.path.expanduser(spec) hits = sorted(h for h in glob.glob(path, recursive=True) if os.path.isfile(h)) if not hits and os.path.isfile(path): hits = [path] if not hits: missing.append(spec) for h in hits: if h not in seen: seen.add(h) files.append(h) return files, missing def sql_str(s): return "'" + str(s).replace("'", "''") + "'" def sql_ident(s): return '"' + str(s).replace('"', '""') + '"' def read_parquet_expr(files): """The one table expression the import reads from: every file in one list, columns matched by name.""" return "read_parquet([%s], union_by_name=true)" % ", ".join(sql_str(f) for f in files) def read_csv_expr(files): """CSV/TSV, header and types auto-detected by DuckDB (its defaults), every file in one list.""" return "read_csv([%s], union_by_name=true)" % ", ".join(sql_str(f) for f in files) CSV_SUFFIXES = (".csv", ".tsv", ".csv.gz", ".tsv.gz", ".csv.zst", ".tsv.zst", ".csv.bz2", ".tsv.bz2") PARQUET_SUFFIXES = (".parquet", ".parq", ".pq") def source_format(path): """'csv' | 'parquet' | None by the file's extension (a URL's query string ignored).""" base = path.split("?", 1)[0].lower() if base.endswith(CSV_SUFFIXES): return "csv" if base.endswith(PARQUET_SUFFIXES): return "parquet" return None def detect_format(files, flag=None): """The one format of the import: `--format csv|parquet` when given, else by extension -- every file must say the same thing. An extension nobody recognises is a usage error (DuckDB's own 'No magic bytes found' told the tester nothing, 2026-09-21); two formats in one list are refused: one statement reads one kind of file.""" if flag and flag != "auto": return flag kinds = {f: source_format(f) for f in files} unknown = [f for f, k in kinds.items() if k is None] if unknown: die_json("unknown_format", "Cannot tell the format of %d file(s) from the extension: %s" % (len(unknown), ", ".join(unknown[:5])), EXIT_USAGE, files=unknown[:20], recognised={"parquet": list(PARQUET_SUFFIXES), "csv": list(CSV_SUFFIXES)}, remedy="Say what they are with --format csv or --format parquet, or rename them (.parquet, .csv, .csv.gz, .tsv).") found = sorted(set(kinds.values())) if len(found) > 1: die_json("mixed_formats", "The files are of two formats (%s); one import reads one format." % ", ".join(found), EXIT_USAGE, by_format={k: [f for f, v in kinds.items() if v == k][:20] for k in found}, remedy="Import each format as its own run (--mode append for the second), or --format to force one reader on all.") return found[0] def source_expr(files, fmt): return read_csv_expr(files) if fmt == "csv" else read_parquet_expr(files) # Security review 2026-10-08 L6: the recipe's SQL used to run verbatim in a local DuckDB, and `lhbox duckdb` handed it to # the binary as an -init file, where a dot command (.shell, .system) runs a program and INSTALL ... FROM '' loads # native code: a redirected or hostile API (a wrong --url, LHBOX_URL) owned the machine. The CLI never runs the server's # SQL text now. recipe_fields() checks each field a statement needs against its shape; recipe_session(), # persistent_secret_statements() and attach_line() build the statements core.py and public.py write from those checked # fields only, quoted with sql_str. _RECIPE_FIELD_RES = { "catalog_alias": re.compile(r"^[a-z0-9_]{1,128}$"), # public_alias() may start with a digit "warehouse_name": re.compile(r"^[a-z0-9][a-z0-9._-]{0,254}$"), "url": re.compile(r"^https?://(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/-]*)?$"), "key": re.compile(r"^[\x21-\x7e]{1,512}$"), # printable ASCII: no NUL, space or newline } def _recipe_field(value, kind, field): """One field of a connection recipe, or exit: a value outside its shape never reaches a statement. The refusal names the field, never its value (a credential, or text meant to be run).""" if not isinstance(value, str) or not _RECIPE_FIELD_RES[kind].match(value): die_json("recipe_refused", "The connection recipe from the server has a %s lhbox does not accept." % field, EXIT_ERROR, field=field, remedy="Check that LHBOX_URL / --url point at your LakehouseBox and update the CLI (lhbox update); " "if both are right, report it: the recipe is not what this CLI expects.") return value def recipe_fields(rec): """The checked fields of a connection recipe (or exit). `_public_reader` is set only by public_catalog_rec (the read-only recipe of GET /v1/public///connection): an owner's own GET /v1/connection of a published catalog also says `public: true`, and gets its own write recipe.""" cred = rec.get("catalog_credential") if isinstance(rec.get("catalog_credential"), dict) else {} f = {"alias": _recipe_field(rec.get("catalog_alias"), "catalog_alias", "catalog_alias"), "bucket": _recipe_field(rec.get("warehouse_name"), "warehouse_name", "warehouse_name"), "uri": _recipe_field(rec.get("catalog_uri"), "url", "catalog_uri"), "client_id": _recipe_field(cred.get("client_id"), "key", "catalog_credential.client_id"), "client_secret": _recipe_field(cred.get("client_secret"), "key", "catalog_credential.client_secret"), "public_reader": rec.get("_public_reader") is True} if f["public_reader"]: storage = _recipe_field(rec.get("public_url"), "url", "public_url") f["oauth"] = f["uri"].rstrip("/") + "/v1/oauth/tokens" else: storage = _recipe_field(rec.get("storage_endpoint"), "url", "storage_endpoint") f["oauth"] = _recipe_field(cred.get("oauth2_server_uri"), "url", "catalog_credential.oauth2_server_uri") edge = rec.get("edge_reads") if isinstance(rec.get("edge_reads"), dict) else None if edge and not f["public_reader"]: # Edge reads (docs/edge-reads.md): the files through the CDN with an edge credential (an hour); the catalog as usual f["edge"] = {"key": _recipe_field(edge.get("access_key_id"), "key", "edge_reads.access_key_id"), "secret": _recipe_field(edge.get("secret_access_key"), "key", "edge_reads.secret_access_key")} files = edge.get("files") if isinstance(files, dict): # the catalog's files bucket through the CDN too (research/100): its own credential, capability and scope f["files_edge"] = {"key": _recipe_field(files.get("access_key_id"), "key", "edge_reads.files.access_key_id"), "secret": _recipe_field(files.get("secret_access_key"), "key", "edge_reads.files.secret_access_key"), "host": _recipe_field(files.get("endpoint"), "url", "edge_reads.files.endpoint").split("://", 1)[-1].rstrip("/"), "bucket": _recipe_field(files.get("bucket"), "warehouse_name", "edge_reads.files.bucket")} bb = rec.get("blob_bucket") if isinstance(bb, str) and _RECIPE_FIELD_RES["warehouse_name"].match(bb) and not f["public_reader"]: f["blob_bucket"] = bb # scopes --persist's S3 secret; one of another shape is left out of it split = urllib.parse.urlsplit(storage) f["storage_host"] = split.netloc if f["public_reader"] else storage.split("://", 1)[-1].rstrip("/") f["use_ssl"] = "true" if split.scheme == "https" else "false" return f # DuckDB's retries for the store's admission control: past a cap the store answers 503, which httpfs retries # http_retries times, waiting ~100 ms x http_retry_backoff^n. The defaults (3, x4) lost 22 % of a busy catalog's queries # at 256 readers on al-lake1; 6 retries lost none at 512 (research/97). The control plane's recipes carry the same line. DUCKDB_RETRIES_SQL = "SET http_retries = 6; SET http_retry_backoff = 4;" def recipe_session(rec, version=None, edge_profile=None): """The DuckDB session statements for a connection recipe, built from its checked fields (never its `sql` text): the extensions, the catalog secret, the storage secret, the ATTACH. The public reader's recipe has a keyless storage secret, ATTACH ... READ_ONLY and secrets named after the alias. `version`: the DuckDB that runs them (the ATTACH option, attach_uri_option). `edge_profile` (Edge reads only): the AWS config profile whose credential_process mints the edge credential, so DuckDB renews it itself (REFRESH auto) instead of holding the recipe's hour-long one (edge_credential_config).""" f = recipe_fields(rec) head = "INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;" retries = DUCKDB_RETRIES_SQL catalog_secret = "CREATE SECRET %s (TYPE ICEBERG, CLIENT_ID %s, CLIENT_SECRET %s, OAUTH2_SERVER_URI %s);" if f["public_reader"]: a = f["alias"] return [head, retries, catalog_secret % (a, sql_str(f["client_id"]), sql_str(f["client_secret"]), sql_str(f["oauth"])), "CREATE SECRET %s_s3 (TYPE S3, KEY_ID '', SECRET '', ENDPOINT %s, URL_STYLE 'path', USE_SSL %s);" % (a, sql_str(f["storage_host"]), f["use_ssl"]), "ATTACH %s AS %s (TYPE ICEBERG, %s %s, SECRET %s, READ_ONLY);" % (sql_str(f["bucket"]), a, attach_uri_option(version), sql_str(f["uri"]), a)] catalog = catalog_secret % ("lhbox", sql_str(f["client_id"]), sql_str(f["client_secret"]), sql_str(f["oauth"])) if f.get("edge"): # the S3 secret is the edge credential, scoped to the bucket; ACCESS_DELEGATION_MODE 'none' keeps DuckDB on it # instead of the store's vended session (research/94 §3.4). With a profile, the credential comes from its # credential_process and DuckDB asks for a new one when the edge answers 403 (ExpiredToken past the hour) where = (sql_str(f["storage_host"]), f["use_ssl"], sql_str("s3://%s/" % f["bucket"])) if edge_profile: s3 = ("CREATE SECRET lhbox_s3 (TYPE S3, PROVIDER credential_chain, CHAIN 'process', PROFILE %s, REFRESH auto, " "ENDPOINT %s, URL_STYLE 'path', USE_SSL %s, REGION 'us-east-1', SCOPE %s);" % ((sql_str(edge_profile),) + where)) head = "INSTALL aws; LOAD aws; " + head else: s3 = ("CREATE SECRET lhbox_s3 (TYPE S3, KEY_ID %s, SECRET %s, ENDPOINT %s, URL_STYLE 'path', USE_SSL %s, " "REGION 'us-east-1', SCOPE %s);" % ((sql_str(f["edge"]["key"]), sql_str(f["edge"]["secret"])) + where)) out = [head, retries, catalog, s3] fe = f.get("files_edge") if fe: # the catalog's files (read_csv('s3:///...')) through the CDN as well, on their own capability: # kept fresh by purges within seconds of a change (research/100) fwhere = (sql_str(fe["host"]), sql_str("s3://%s/" % fe["bucket"])) if edge_profile: out.append("CREATE SECRET lhbox_files_s3 (TYPE S3, PROVIDER credential_chain, CHAIN 'process', PROFILE %s, " "REFRESH auto, ENDPOINT %s, URL_STYLE 'path', USE_SSL true, REGION 'us-east-1', SCOPE %s);" % ((sql_str(edge_profile + EDGE_FILES_SUFFIX),) + fwhere)) else: out.append("CREATE SECRET lhbox_files_s3 (TYPE S3, KEY_ID %s, SECRET %s, ENDPOINT %s, URL_STYLE 'path', " "USE_SSL true, REGION 'us-east-1', SCOPE %s);" % ((sql_str(fe["key"]), sql_str(fe["secret"])) + fwhere)) return out + [attach_line(f, version=version, delegation="none")] return [head, retries, catalog, "CREATE SECRET lhbox_s3 (TYPE S3, KEY_ID %s, SECRET %s, ENDPOINT %s, URL_STYLE 'path', USE_SSL %s, REGION 'us-east-1');" % (sql_str(f["client_id"]), sql_str(f["client_secret"]), sql_str(f["storage_host"]), f["use_ssl"]), attach_line(f, version=version)] # ---------------------------------------------------------------- Edge reads: the edge credential renewed in the shell # An edge credential lives an hour (docs/edge-reads.md). `lhbox duckdb --edge` does not hand DuckDB the recipe's one: # DuckDB's S3 secret takes it from an AWS config profile whose credential_process is this CLI # (`lhbox duckdb --catalog --edge --credential-process`, which prints a fresh one in the AWS process format), with # REFRESH auto: when the edge answers 403 past the hour, DuckDB runs the process again and retries (measured 2026-10-25 # with DuckDB 1.5.5 and 2.0.0: a 403, the process run again, the same request answered). The credential never touches # the disk; the config file holds the command only, in a private directory removed when the shell ends. The person's own # AWS config is copied into it, so their own profiles keep working in that shell. EDGE_PROFILE = "lhbox-edge-reads" EDGE_FILES_SUFFIX = "-files" # the files bucket's profile: EDGE_PROFILE + this, its process run with --files def edge_credential_command(args, wid, files=False): """The command line DuckDB runs for a new edge credential: this lhbox (self_command), the same API and the profile in force now, pinned (_self_args: a later `lhbox profile use` elsewhere must not move a running shell to another key). files: the catalog's files bucket's credential (--files).""" return _shell_line(self_command() + _self_args(args) + ["duckdb", "--catalog", wid, "--edge", "--credential-process"] + (["--files"] if files else [])) def edge_renewal_possible(args, version): """Can this shell renew its edge credential itself? Not on a DuckDB older than 1.5.5 (credential_chain's REFRESH was measured on 1.5.5 and 2.0.0), and not with a key given as --api-key: the renewal would need it in DuckDB's own environment, where any SQL in the shell reads it with getenv() (high review of #1883, finding 4). Both keep the recipe's own credential, for its hour.""" return version is not None and not version < DUCKDB_MIN and not getattr(args, "api_key", None) # a KNOWN 1.5.5+ def edge_credential_config(args, wid): """(directory, environment) for the shell: a private directory with an AWS config whose EDGE_PROFILE runs edge_credential_command, after the person's own config (when it is readable); the environment points DuckDB at it. The renewal finds its key as this run did, from LHBOX_API_KEY or the saved login (edge_renewal_possible).""" d = tempfile.mkdtemp(prefix="lhbox-edge-") # 0700 own = os.environ.get("AWS_CONFIG_FILE") or os.path.expanduser("~/.aws/config") text = "" try: with open(own) as fh: text = fh.read() except (OSError, UnicodeDecodeError): text = "" if text and not text.endswith("\n"): text += "\n" path = os.path.join(d, "config") fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w") as fh: fh.write(text + "[profile %s]\ncredential_process = %s\n" % (EDGE_PROFILE, edge_credential_command(args, wid)) + "[profile %s]\ncredential_process = %s\n" % (EDGE_PROFILE + EDGE_FILES_SUFFIX, edge_credential_command(args, wid, files=True))) return d, dict(os.environ, AWS_CONFIG_FILE=path) def edge_process_credential(rec, files=False): """The AWS credential_process answer for an edge recipe: {Version 1, AccessKeyId, SecretAccessKey, Expiration}. files: the catalog's files bucket's credential (edge_reads.files) instead of its tables'.""" f = recipe_fields(rec) cred = f.get("files_edge") if files else f.get("edge") if not cred: die_json("recipe_refused", "The connection recipe from the server has no edge credential%s." % ( " for the catalog's files" if files else ""), EXIT_ERROR, field="edge_reads", remedy="Check that edge caching is on for this catalog (its Settings on the account page).") exp = ((rec.get("edge_reads") or {}).get("files") or {}).get("expires_at") if files else (rec.get("edge_reads") or {}).get("expires_at") out = {"Version": 1, "AccessKeyId": cred["key"], "SecretAccessKey": cred["secret"]} if isinstance(exp, str) and re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$", exp): out["Expiration"] = exp return out # ---------------------------------------------------------------- the catalog token (POST /v1/catalog-token) # platform/docs/table-grants.md "A catalog token": a caller whose access to a catalog is namespace or table grants gets a # catalog bearer minted from its OWN scoped identity (about an hour). A service account has no other engine path (its # recipe is vended-only); a scoped member's static pair works too, but the bearer keeps the pair out of the DuckDB session. # `lhbox duckdb` never hands the bearer to DuckDB as text: it serves it from a loopback OAuth2 token endpoint for the life # of the shell (CatalogTokenBroker), which DuckDB asks again when the token it holds expires (measured 2026-10-16 with # DuckDB 1.5.5: it re-asks OAUTH2_SERVER_URI after each expires_in). The broker renews the bearer in the background before # it is due, so DuckDB's request is always answered at once (high review of #1488, 8). CATALOG_TOKEN_RE = re.compile(r"^[A-Za-z0-9._~+/=-]{16,16384}$") # a JWT or an opaque bearer: no quote, space or newline CATALOG_TOKEN_ENV_RE = re.compile(r"^LHBOX_[A-Z0-9_]{1,160}_CATALOG_TOKEN$") CATALOG_TOKEN_MARGIN = 300 # a bearer is renewed when it has less than this left (or half its life when shorter) CATALOG_TOKEN_MIN_LIFE = 60 # an answer that leaves DuckDB less than this is no token at all CATALOG_TOKEN_TEST_MIN_LIFE = 10 # the lowest the test aid LHBOX_TEST_CATALOG_TOKEN_MIN_LIFE may set the renewal floor to CATALOG_TOKEN_RETRY = (5, 15, 30, 60, 120) # backoff of the background renewal after a transient failure, seconds SCOPED_VIAS = ("namespace", "table") # the route's refusals a scoped MEMBER's shell answers with its own pair recipe instead (high review of #1488, 2): the # token is a nicety for a member, never the only way in CATALOG_TOKEN_FALLBACK = ("enterprise_feature", "rate_limited", "catalog_token_engine_only", "catalog_token_not_offered", "mcp_no_catalog_token") def wants_catalog_token(rec): """Does this recipe's holder reach the catalog through namespace or table grants -- the callers POST /v1/catalog-token serves? A vended-only recipe says so by naming the route (`catalog_token`); a member's or a token's static recipe by level_via namespace/table (a catalog-level holder is refused the route, 409 catalog_token_not_offered).""" if not isinstance(rec, dict): return False if rec.get("credentials") == "vended_only": return isinstance(rec.get("catalog_token"), dict) return rec.get("level_via") in SCOPED_VIAS def catalog_token_fields(ans): """(fields, None) for a well-formed answer of POST /v1/catalog-token, or (None, (field, message)): the one check of every field before it reaches DuckDB or a terminal (the bearer's shape, its lifetime, the variable the samples read it from, the recipe fields), shared by the first mint and the broker's renewals (high review of #1488, 9).""" if not isinstance(ans, dict): return None, ("token", "The catalog token answer from the server is not an object.") tok = ans.get("token") if not isinstance(tok, str) or not CATALOG_TOKEN_RE.match(tok): return None, ("token", "The catalog token answer from the server has a token lhbox does not accept.") try: life = int(ans.get("expires_in")) except (TypeError, ValueError): life = 0 if life < CATALOG_TOKEN_MIN_LIFE: return None, ("expires_in", "The catalog token answer from the server says it expires in %d s." % life) var = ans["token_env"].get("token") if isinstance(ans.get("token_env"), dict) else None if var is not None and not (isinstance(var, str) and CATALOG_TOKEN_ENV_RE.match(var)): return None, ("token_env.token", "The catalog token answer names an environment variable lhbox does not accept.") out = {"token": tok, "expires_in": life, "env": var} for key, field, kind in (("alias", "catalog_alias", "catalog_alias"), ("bucket", "warehouse_name", "warehouse_name"), ("uri", "catalog_uri", "url")): v = ans.get(field) if not isinstance(v, str) or not _RECIPE_FIELD_RES[kind].match(v): return None, (field, "The catalog token answer from the server has a %s lhbox does not accept." % field) out[key] = v return out, None def _checked_catalog_token(ans): fields, problem = catalog_token_fields(ans) if problem: die_json("recipe_refused", problem[1], EXIT_ERROR, field=problem[0], remedy="Check that LHBOX_URL / --url point at your LakehouseBox and update the CLI (lhbox update); if both " "are right, report it.") return fields def mint_catalog_token(args, wid): """POST /v1/catalog-token for the catalog `wid`, answered as it is (a refusal is the usual envelope and exit code).""" return request(args, "POST", "/v1/catalog-token", {"warehouse_id": wid}, timeout=90) def masked_catalog_token(ans): """The route's answer with the bearer shown as ******** (it is a credential for about an hour): --show-secrets opts in.""" if not isinstance(ans, dict) or not ans.get("token"): return ans return dict(ans, token="********", secrets_masked=True, secrets_note="the catalog token is shown as ********: --show-secrets prints it (pipe it rather than show " "it: `lhbox connect --show-secrets --human | duckdb`); `lhbox duckdb` attaches with it without " "showing it, and renews it while the shell runs") def quiet_catalog_mint(args, wid): """A renewal for the broker, on its thread, printing nothing (a thread-local silence: no process-global stream is swapped, high review of #1488, 6). -> ("ok", fields) | ("refused", status) -- the grant, the key or the plan is gone: 401/403/404 -- | ("transient", why) -- the network, a timeout, a 429 or 5xx, the directory: worth another try.""" _SILENT.on = True try: st, ans = request_status(args, "POST", "/v1/catalog-token", {"warehouse_id": wid}, timeout=30) except SystemExit: return "transient", "unreachable" except Exception as exc: # noqa: BLE001 - nothing escapes the renewal thread return "transient", type(exc).__name__ finally: _SILENT.on = False if st == 200: fields, problem = catalog_token_fields(ans) return ("ok", fields) if fields else ("transient", "bad answer: %s" % problem[0]) if st in (401, 403, 404): return "refused", st return "transient", "HTTP %d" % st class CatalogTokenBroker: """A loopback OAuth2 token endpoint (127.0.0.1, a free port, for the life of one `lhbox duckdb` shell) that answers DuckDB's client-credentials request with the current catalog bearer. DuckDB holds only this endpoint's one-time client id and secret (random, never on screen, in argv or on disk: the init FIFO carries them), so another local user who finds the port gets nothing. A background thread renews the bearer when it has CATALOG_TOKEN_MARGIN left (half its life when shorter), retrying a transient failure with backoff while the current one is still valid; DuckDB is told to come back just after the renewal point, and every request is answered at once from what the broker holds: 200 the current bearer; 503 temporarily_unavailable when it expired and renewal keeps failing for a transient reason (DuckDB's next statement asks again); 401 invalid_client once LakehouseBox REFUSED a renewal (401/403/404: the grant revoked, the key deleted), never the old bearer again. `renew_before` (LHBOX_CATALOG_TOKEN_RENEW_BEFORE, a test aid) moves the renewal point, clamped to leave the bearer at least CATALOG_TOKEN_MIN_LIFE (high review of #1488, 7). `min_life` (LHBOX_TEST_CATALOG_TOKEN_MIN_LIFE, honoured only together with renew_before, so the stack suite's Phase 18 waits seconds, not minutes) can only LOWER that floor, never below CATALOG_TOKEN_TEST_MIN_LIFE; it is ignored without renew_before, so a session without the test aids is unchanged.""" def __init__(self, mint, first, renew_before=None, clock=time.time, min_life=None): import secrets as _secrets self._mint, self._clock, self._renew_override = mint, clock, renew_before self._min_life = CATALOG_TOKEN_MIN_LIFE if renew_before is not None and min_life is not None: self._min_life = max(CATALOG_TOKEN_TEST_MIN_LIFE, min(int(min_life), CATALOG_TOKEN_MIN_LIFE)) self._lock = threading.Lock() self._wake = threading.Event() self._stop = threading.Event() self._tok, self._exp, self._renew_at = None, 0.0, 0 self._keep(first, clock()) self.client_id = "lhbox-" + _secrets.token_hex(8) self.client_secret = _secrets.token_urlsafe(32) self.requests, self.mints, self.refusals = 0, 0, 0 self.refused = None # the status of the renewal LakehouseBox refused (final) self.failing = None # why the latest renewal failed transiently; None once one succeeds self._failures_in_a_row = 0 self._server = None def _keep(self, got, now): life = int(got["expires_in"]) self._tok, self._exp = got["token"], now + life default = min(CATALOG_TOKEN_MARGIN, life // 2) if self._renew_override is None: self._renew_at = default else: self._renew_at = max(0, min(int(self._renew_override), life - self._min_life)) def due_in(self, now=None): """Seconds until the next renewal attempt (0: now).""" now = self._clock() if now is None else now with self._lock: if self.refused is not None: return None if self._failures_in_a_row: return CATALOG_TOKEN_RETRY[min(self._failures_in_a_row, len(CATALOG_TOKEN_RETRY)) - 1] return max(0.0, self._exp - self._renew_at - now) def renew(self): """One renewal attempt (the background thread's step; the unit tests call it directly).""" kind, value = self._mint() with self._lock: if kind == "ok": self._keep(value, self._clock()) self.mints += 1 self.failing, self._failures_in_a_row = None, 0 elif kind == "refused": self.refused, self._tok, self._exp = value, None, 0.0 else: self.failing = value self._failures_in_a_row += 1 return kind def answer(self, client_id, client_secret, grant_type): """(status, body) for one token request -- the whole decision, without HTTP (the unit tests drive it).""" self.requests += 1 ok = (hmac.compare_digest(str(client_id or "").encode(), self.client_id.encode()) and hmac.compare_digest(str(client_secret or "").encode(), self.client_secret.encode())) if not ok: self.refusals += 1 return 401, {"error": "invalid_client"} if grant_type != "client_credentials": return 400, {"error": "unsupported_grant_type"} now = self._clock() with self._lock: if self.refused is not None: return 401, {"error": "invalid_client", "error_description": "LakehouseBox refused a new catalog token"} left = self._exp - now if not self._tok or left < 1: return 503, {"error": "temporarily_unavailable", "error_description": "the catalog token expired and could not be renewed yet; try again"} # come back just after the renewal point; if it has passed (renewal pending or failing), soon tell = left - self._renew_at tell = tell + 1 if tell > 0 else min(CATALOG_TOKEN_RETRY[0], left - 1) return 200, {"access_token": self._tok, "token_type": "bearer", "expires_in": max(1, int(tell))} def _loop(self): while not self._stop.is_set(): wait = self.due_in() if wait is None: return if wait > 0 and self._stop.wait(min(wait, 3600)): return if self.due_in() == 0 or self._failures_in_a_row: try: self.renew() except Exception: # noqa: BLE001 - the thread never dies of a renewal with self._lock: self.failing, self._failures_in_a_row = "error", self._failures_in_a_row + 1 def start(self): import http.server broker = self class Server(http.server.ThreadingHTTPServer): daemon_threads = True def handle_error(self, request, client_address): # nothing on the terminal the shell is using pass class Handler(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass def _send(self, status, body): data = json.dumps(body).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def _refuse(self, status, body): """Answer without having read the request body, then read and drop what the client already sent before the socket closes: closing over unread bytes sends a reset, and under gVisor (bunny) that reset can reach the client before it reads this answer (#2465). Bounded (1 MiB, 2 s) so a client that keeps sending cannot hold the thread.""" self.close_connection = True self._send(status, body) try: self.connection.shutdown(socket.SHUT_WR) self.connection.settimeout(0.5) left, until = 1 << 20, time.monotonic() + 2 while left > 0 and time.monotonic() < until: chunk = self.rfile.read1(min(65536, left)) if not chunk: break left -= len(chunk) except OSError: pass def do_POST(self): # noqa: N802 - the stdlib's name try: raw_len = self.headers.get("Content-Length") or "0" if not raw_len.isdigit() or int(raw_len) > 65536: return self._refuse(400, {"error": "invalid_request"}) form = dict(urllib.parse.parse_qsl(self.rfile.read(int(raw_len)).decode("utf-8", "replace"))) cid, csec = form.get("client_id"), form.get("client_secret") auth = self.headers.get("Authorization") or "" if auth.lower().startswith("basic "): try: cid, _, csec = base64.b64decode(auth[6:].strip(), validate=True).decode().partition(":") cid, csec = urllib.parse.unquote(cid), urllib.parse.unquote(csec) except (ValueError, UnicodeDecodeError): cid = csec = None if self.path.split("?")[0] != "/v1/oauth/tokens": return self._send(404, {"error": "not_found"}) self._send(*broker.answer(cid, csec, form.get("grant_type"))) except Exception: # noqa: BLE001 - never a traceback into the shell try: self._send(500, {"error": "server_error"}) except Exception: # noqa: BLE001 pass def do_GET(self): # noqa: N802 self._send(405, {"error": "method_not_allowed"}) self._server = Server(("127.0.0.1", 0), Handler) threading.Thread(target=self._server.serve_forever, name="lhbox-catalog-token", daemon=True).start() threading.Thread(target=self._loop, name="lhbox-catalog-token-renew", daemon=True).start() return self @property def token_uri(self): return "http://127.0.0.1:%d/v1/oauth/tokens" % self._server.server_address[1] def stop(self): self._stop.set() if self._server is not None: self._server.shutdown() self._server.server_close() def outcome(self): """What to tell the person when the shell ends: the FINAL state, never a failure a later renewal mended.""" if self.refused is not None: return "lhbox: LakehouseBox refused a new catalog token (HTTP %s: a revoked grant, or a deleted key)" % self.refused if self.failing and self._exp <= self._clock(): return "lhbox: the catalog token could not be renewed (%s); run lhbox duckdb again" % self.failing if self.mints: return "lhbox: the catalog token was renewed %d time(s) during this session" % self.mints return None def token_session(fields, token_uri, client_id, client_secret, version=None): """The DuckDB session statements for a catalog token served by the broker: the extensions, an ICEBERG secret whose OAUTH2_SERVER_URI is the loopback endpoint (DuckDB asks it again at each expiry), the ATTACH with vended credentials (the catalog vends each table's storage session: no S3 key in the session).""" return ["INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;", DUCKDB_RETRIES_SQL, "CREATE SECRET lhbox (TYPE ICEBERG, CLIENT_ID %s, CLIENT_SECRET %s, OAUTH2_SERVER_URI %s);" % (sql_str(client_id), sql_str(client_secret), sql_str(token_uri)), "ATTACH %s AS %s (TYPE ICEBERG, %s %s, SECRET lhbox, ACCESS_DELEGATION_MODE 'vended_credentials');" % (sql_str(fields["bucket"]), fields["alias"], attach_uri_option(version), sql_str(fields["uri"]))] def _import_duckdb(): """The python module, or None. A seam: tests replace it.""" try: import duckdb # noqa: F401 -- optional at run time; the CLI itself stays stdlib-only return duckdb except ImportError: return None # The in-process engine's session keeps each remote file's HTTP metadata and each Parquet footer (PLAN 23), so a repeated # read does not re-fetch them (research/35 §10: repeats 317-358 -> 16-47 ms). Iceberg data files never change once # written (compaction and expiry write new names). The interactive shell does NOT get them: it can live for hours and read # a blob bucket's key that someone overwrites, and the HTTP cache would keep the old size (review of PLAN 23's PR). DUCKDB_SESSION_CACHES = ["SET enable_http_metadata_cache = true;", "SET parquet_metadata_cache = true;"] def _session_caches(con): for st in DUCKDB_SESSION_CACHES: try: con.execute(st) except Exception: # noqa: BLE001 - a DuckDB without it (--no-version-check) pass class DuckDBModule: """DuckDB in this process (the `duckdb` module): one connection, so ATTACH happens once.""" def __init__(self, mod): self.mod = mod # no progress bar: it draws on this process's stdout, where --json output goes (the Portolan import, 2026-09-28) self.con = mod.connect() self.con.execute("SET enable_progress_bar = false") _session_caches(self.con) self.version = _parse_version(mod.__version__) self.interpreter = sys.executable self.where = "python module duckdb %s via %s" % (mod.__version__, sys.executable) def run(self, sql, attached=False): """Execute one statement -> its rows as dicts (empty for a statement without a result set).""" with _NativeStdoutToStderr(): cur = self.con.execute(sql) if not cur.description: return [] names = [d[0] for d in cur.description] return [dict(zip(names, row)) for row in cur.fetchall()] def session(self, statements): self._session = list(statements) with _NativeStdoutToStderr(): for st in statements: self.con.execute(st) def refresh(self): """A new connection with the session replayed: the attached catalog keeps the table metadata it loaded, so table properties set through it (the codec) reach the writer only after a re-attach (measured, research/54 §3).""" old, self.con = self.con, self.mod.connect() old.close() self.con.execute("SET enable_progress_bar = false") _session_caches(self.con) self.session(getattr(self, "_session", [])) class _NativeStdoutToStderr: """While DuckDB runs in THIS process and the output is for a machine, file descriptor 1 points at stderr: whatever the C++ side prints (a progress bar a setting turned back on, an extension's notice) cannot reach the stdout that carries the one JSON document. Python's own sys.stdout is flushed first and fd 1 is back when the block ends.""" def __enter__(self): self.saved = None if not _json_mode(): return self try: sys.stdout.flush() except (AttributeError, OSError, ValueError): pass try: # the descriptors themselves, whatever sys.stdout is: DuckDB's C++ side writes to fd 1 self.fd = 1 self.saved = os.dup(1) os.dup2(2, 1) except OSError: self.saved = None return self def __exit__(self, *exc): if self.saved is not None: # C stdio buffers a pipe fully: what DuckDB printf'd must leave while fd 1 still points at stderr, or it # reaches the real stdout at exit, after the JSON document (high review, finding 7) try: import ctypes ctypes.CDLL(None).fflush(None) except Exception: # noqa: BLE001 - best effort; no libc symbol here pass os.dup2(self.saved, self.fd) os.close(self.saved) return False # The answer is ONE line starting with _PY_ANSWER: DuckDB's progress bar went to the child's stdout and made a 29,607-row # import that HAD committed report "unreadable answer ... Safe to retry" (the Portolan import, 2026-09-28). The bar is # turned off as well; the marker is what makes any other output harmless. _PY_ANSWER = "LHBOX-ANSWER:" _PY_RUNNER = "\n".join([ "import json, sys", "import duckdb", "req = json.load(sys.stdin)", "con = duckdb.connect()", "con.execute('SET enable_progress_bar = false')", "for st in req['session']:", " con.execute(st)", "cur = con.execute(req['sql'])", "rows = []", "if cur.description:", " names = [d[0] for d in cur.description]", " rows = [dict(zip(names, r)) for r in cur.fetchall()]", "sys.stdout.write('\\n' + %r + json.dumps(rows, default=str) + '\\n')" % _PY_ANSWER, ]) class DuckDBPython: """The `duckdb` module of ANOTHER interpreter (`--python PATH`, LHBOX_PYTHON): a fresh process per statement running _PY_RUNNER, the session statements (secrets, ATTACH) and the statement handed over as JSON on stdin -- nothing secret in argv. The agent's own environment usually holds the DuckDB it will read the table with; this imports with that one instead of whatever python runs lhbox.""" def __init__(self, exe): self.exe = exe self.interpreter = exe # the path as given runs every statement; the child names itself (its sys.executable), never a realpath() v, raw, reported, _ = _python_duckdb(exe) self.version = v self.where = "python module duckdb %s via %s" % (raw or "?", reported) self._session = [] def refresh(self): """Nothing to do: every statement runs in a fresh process that attaches anew.""" def session(self, statements): self._session = list(statements) def run(self, sql, attached=False): req = {"session": self._session if attached else [], "sql": sql} try: r = subprocess.run([self.exe, "-c", _PY_RUNNER], input=json.dumps(req), capture_output=True, text=True) except OSError as e: raise DuckDBFailure("cannot run %s: %s" % (self.exe, e)) if r.returncode != 0: lines = (r.stderr or r.stdout or "python exited %d" % r.returncode).strip().splitlines() raise DuckDBFailure(lines[-1] if lines else "python exited %d" % r.returncode) lines = (r.stdout or "").splitlines() answers = [ln[len(_PY_ANSWER):] for ln in lines if ln.startswith(_PY_ANSWER)] # no marker (an older runner, a stand-in): the last line that is JSON answers = answers or [ln for ln in lines if ln.strip().startswith("[")] try: return json.loads(answers[-1]) except (IndexError, ValueError): # the statement ran to the end (exit 0) and its answer is missing: never a plain failure, it may have committed raise DuckDBFailure("unreadable answer from %s (the statement exited 0 and may have committed): %s" % (self.exe, (r.stdout or "")[-200:])) class DuckDBBinary: """The `duckdb` binary: a fresh process per statement, so the session statements (secrets, ATTACH) are replayed on stdin before a statement that needs the catalog. Nothing secret is ever in argv.""" def __init__(self, exe): self.exe = exe self.interpreter = None v, raw = _version_of([exe, "--version"]) self.version = v self.where = "duckdb binary %s (%s)" % (exe, raw or "version unknown") self._session = [] def refresh(self): """Nothing to do: every statement runs in a fresh process that attaches anew.""" def session(self, statements): self._session = list(statements) def run(self, sql, attached=False): script = "\n".join(["SET enable_progress_bar = false;"] + (self._session if attached else []) + [sql]) + "\n" try: r = subprocess.run([self.exe, "-bail", "-json"], input=script, capture_output=True, text=True, timeout=None, env={**os.environ, "DUCKDB_AGENT_MODE": "0"}) except OSError as e: raise DuckDBFailure("cannot run %s: %s" % (self.exe, e)) if r.returncode != 0: raise DuckDBFailure((r.stderr or r.stdout or "duckdb exited %d" % r.returncode).strip()) # `-json` prints one JSON array per statement with a result set; the last one is ours dec, pos, last, text = json.JSONDecoder(), 0, [], r.stdout.strip() while pos < len(text): while pos < len(text) and text[pos] in " \r\n\t": pos += 1 if pos >= len(text): break try: obj, pos = dec.raw_decode(text, pos) except ValueError: # not JSON (a progress line, a notice): skip to the next array and keep the last answer that parses nxt = text.find("[", pos + 1) if nxt < 0: break pos = nxt continue last = obj return last if isinstance(last, list) else [] class DuckDBFailure(Exception): pass def duckdb_engine(args): """The DuckDB that runs the import: `--python PATH` / LHBOX_PYTHON name the interpreter whose duckdb module is used (in this process when it is the one running lhbox, as a subprocess otherwise); without them the python module of THIS interpreter when importable, else the `duckdb` binary on PATH; nothing -> exit 1 naming every place looked. Below 1.5.5 -> exit 1 naming the interpreter that was used and how to upgrade THAT one, unless --no-version-check (the same floor `connect` and `doctor` apply).""" wanted = getattr(args, "python", None) or _env("PYTHON") if wanted: exe = shutil.which(wanted) or (os.path.expanduser(wanted) if os.path.isfile(os.path.expanduser(wanted)) else None) if not exe: die_json("python_not_found", "No interpreter at %r (--python / LHBOX_PYTHON)." % wanted, EXIT_USAGE, remedy="Pass the path of a python that has duckdb installed, or unset LHBOX_PYTHON to use the one running lhbox.") # The very path of the interpreter running lhbox -> its module, in this process. The path as given, never # realpath(): a venv's bin/python is a symlink to the base interpreter, so the venv, the base and every other # venv resolve to ONE binary while each has its own site-packages; `--python /tmp/ddb155/bin/python` (1.5.5) # was answered with the Homebrew python3's 1.5.0 that ran lhbox that way (2026-09-23). The flag names an # environment: another path is another environment, probed and run as a subprocess. if os.path.abspath(exe) == os.path.abspath(sys.executable or "/") and _import_duckdb() is not None: engine = DuckDBModule(_import_duckdb()) else: engine = DuckDBPython(exe) if engine.version is None: die_json("duckdb_not_found", "%s has no duckdb module (`%s -c 'import duckdb'` failed)." % (exe, exe), EXIT_ERROR, interpreter=exe, remedy="%s -m pip install 'duckdb>=%s', or point --python / LHBOX_PYTHON at an interpreter that has it." % (exe, _dotted(DUCKDB_MIN))) else: mod = _import_duckdb() if mod is not None: engine = DuckDBModule(mod) else: exe = shutil.which("duckdb") if not exe: die_json("duckdb_not_found", "No DuckDB on this machine: neither the python module (%s -c 'import duckdb') nor a `duckdb` binary on PATH." % (sys.executable or "python3"), EXIT_ERROR, interpreter=sys.executable, remedy="pip install 'duckdb>=%s' into the python that runs lhbox (%s), or --python PATH / LHBOX_PYTHON=PATH " "to use another interpreter's duckdb, or install the duckdb binary (brew install duckdb) and put it on PATH." % (_dotted(DUCKDB_MIN), sys.executable or "python3")) engine = DuckDBBinary(exe) if engine.version and engine.version < DUCKDB_MIN and not getattr(args, "no_version_check", False): upgrade = ("brew upgrade duckdb (or reinstall the binary from duckdb.org)" if engine.interpreter is None else "%s -m pip install -U 'duckdb>=%s'" % (engine.interpreter, _dotted(DUCKDB_MIN))) die_json("duckdb_too_old", "DuckDB %s (%s) is older than %s: it writes manifest lists the catalog's maintenance cannot read, so the " "table it writes is never compacted or expired." % (_dotted(engine.version), engine.where, _dotted(DUCKDB_MIN)), EXIT_ERROR, found=_dotted(engine.version), minimum=_dotted(DUCKDB_MIN), interpreter=engine.interpreter, remedy="%s (upgrades the DuckDB that was used); or --python PATH / LHBOX_PYTHON=PATH to import with another " "interpreter's duckdb (%s or newer); --no-version-check imports anyway." % (upgrade, _dotted(DUCKDB_MIN))) return engine _DUCKDB_RETRYABLE = ("Could not connect", "IO Error", "timed out", "Connection", "connection reset", "Broken pipe") def _duckdb_retryable(text): """Is a DuckDB error the network's or the server's (retry: 5), or the request's (fix it: 1)? An HTTP status in the message decides when there is one: 5xx, 408 and 429 are retryable, and 409 when it is a commit conflict (an optimistic commit lost to another writer, maintenance included); any other 4xx -- a catalog 400 relayed as "HTTP 400" -- is the request, which the old substring test ("HTTP" in text) answered with "safe to retry".""" # URLs go first: in http://127.0.0.1/ the scheme followed by the address read as "HTTP 127" (#3061) m = re.search(r"\b(?:HTTP|status(?: code)?)\D{0,12}([1-5]\d\d)\b", re.sub(r"\b[a-z][a-z0-9+.-]*://\S+", " ", text, flags=re.I), re.I) if m: st = int(m.group(1)) if st >= 500 or st in (408, 429): return True if st == 409: return "commit" in text.lower() and "exist" not in text.lower() return False return any(w.lower() in text.lower() for w in _DUCKDB_RETRYABLE) def _duckdb_die(exc, remedy=None, **extra): """A DuckDB error as the typed JSON the caller expects; the class is in the exit code: a network or storage failure is retryable (5), a binder or conversion error is the request (1). Only for a statement that did NOT commit (import_insert_failed decides that for the one data commit). `remedy` replaces the default one (a setup failure after the table was created says so).""" text = str(exc).strip() retry = _duckdb_retryable(text) if retry and "outcome" not in extra: extra["outcome"] = "failed" die_json("duckdb_error", "DuckDB failed: " + (text.splitlines() or ["?"])[0][:400], EXIT_SERVER if retry else EXIT_ERROR, duckdb_message=text[:2000], remedy=remedy or ("Safe to retry with backoff." if retry else "Fix the statement or the files (the message names the column or the type); a retry unchanged " "fails the same way."), **extra) SNAPSHOT_LOOKBACK = 50 # GET /v1/table?snapshots= (its maximum): the snapshots import_insert_failed compares ROWS_NOT_AVAILABLE = "row count not available for this table" def _rows_known(t): """A table answer's `rows` when it is an exact count, else None (#2566: GET /v1/table answers `rows: null`, or `rows_is_exact: false`, when a table's manifests are past the read budget).""" if not isinstance(t, dict) or t.get("rows_is_exact") is False or not isinstance(t.get("rows"), int): return None return t["rows"] def _rows_appended(before, after): """Rows an import added: after minus before, or None when either side is unknown (never 0 or negative for that).""" b, a = _rows_known(before), _rows_known(after) return None if a is None or b is None else a - b def _import_append_since(before, now): """(snapshot id, rows added) of THE append with rows that `now` has and `before` did not; None when there is none; "ambiguous" when the log cannot tell: two or more such appends (another writer -- a sink roll, another agent -- appended too, so which one is ours is not known), or `before`'s newest snapshot is no longer in the window (more than SNAPSHOT_LOOKBACK commits since: ours could have scrolled out). High review, finding 4: counting ANY new append as ours took a concurrent writer's rows for the import's and reported success with the rows lost. Without snapshot_log (an older control plane): the current snapshot, when it moved and is such an append.""" def rows(n): try: return int(n or 0) except (TypeError, ValueError): return 0 if isinstance(now.get("snapshot_log"), list): seen = {str(e.get("snapshot_id")) for e in before.get("snapshot_log") or []} seen.add(str(before.get("current_snapshot_id"))) ids_now = {str(e.get("snapshot_id")) for e in now["snapshot_log"]} newest_before = next(iter(before.get("snapshot_log") or []), None) if newest_before and str(newest_before.get("snapshot_id")) not in ids_now and len(now["snapshot_log"]) >= SNAPSHOT_LOOKBACK: return "ambiguous" new = [(str(e.get("snapshot_id")), rows(e.get("added_records"))) for e in now["snapshot_log"] # newest first if str(e.get("snapshot_id")) not in seen and e.get("operation") == "append" and rows(e.get("added_records")) > 0] if len(new) > 1: return "ambiguous" return new[0] if new else None summary = now.get("current_snapshot_summary") or {} moved = now.get("current_snapshot_id") is not None and now.get("current_snapshot_id") != before.get("current_snapshot_id") if moved and summary.get("operation") == "append" and rows(summary.get("added-records")) > 0: return str(now.get("current_snapshot_id")), rows(summary.get("added-records")) return None def import_insert_failed(args, q, before, exc, created_remedy=None): """The import's ONE data commit (the INSERT) raised. An error can arrive after the commit landed (an answer DuckDB printed that could not be read, a connection cut after the catalog accepted it), and then "retry" means a second create (409) or, with --mode append, every row twice (the Portolan import of 2026-09-28: 29,607 rows in, "Safe to retry" said). So the table is asked first. Committed = the CURRENT snapshot is not the one before the import and is an `append` that added rows -- never the snapshot COUNT, which maintenance moves both ways (a compaction adds a `replace` snapshot, expiry removes old ones; high review of this change, finding 1). Committed -> a warning and the caller carries on with the report; not -> the usual error; no answer -> an error that says the commit is UNKNOWN and how to check, never "safe to retry". A concurrent writer's own append looks the same: the warning names the snapshot and its row count so it can be checked. Returns only when committed. Every snapshot since the import started is looked at, not only the current one (docs/proposals/cli-consistency.md): maintenance commits optimistically, so a compaction can land right after our append and make the CURRENT snapshot a `replace`, which read "not committed" and "safe to retry" -- every row twice with --mode append. `before` carries the snapshot_log it was read with (?snapshots=50); a control plane without snapshot_log gets the current-snapshot rule. `created_remedy` (#2019): this import created the table (--mode create) and the INSERT then failed; a re-run unchanged answers table_exists, so a failure that did not commit says the table exists and how to go on, never "safe to retry".""" text = str(exc).strip() st, now = request_status(args, "GET", "/v1/table?" + q + "&snapshots=%d" % SNAPSHOT_LOOKBACK) if st == 200 and isinstance(now, dict): landed = _import_append_since(before, now) if landed == "ambiguous": ns_name = dict(urllib.parse.parse_qsl(q)) die_json("import_outcome_unknown", "DuckDB failed during the commit, and the table's snapshot log cannot tell whether " "the rows are in: other appends landed during the import, or more than %d commits did. %s" % (SNAPSHOT_LOOKBACK, text.splitlines()[0][:300] if text else ""), EXIT_SERVER, committed=None, outcome="unknown", duckdb_message=text[:2000], rows_before=before.get("rows"), current_snapshot_id_before=before.get("current_snapshot_id"), remedy="Check before retrying: lhbox table get %s.%s --catalog %s (and its snapshot log: GET /v1/table" "?snapshots=50): look for an append of this import's row count since snapshot %s. A retry with " "--mode append duplicates every row if it did land." % (ns_name.get("namespace"), ns_name.get("name"), ns_name.get("catalog"), before.get("current_snapshot_id"))) if landed: print("warning: DuckDB reported an error AFTER the commit landed: snapshot %s is an append of %d row(s) made since " "the import started (%s). The rows are in; do not retry (if another writer appended to this table at the " "same moment, check with lhbox table get)." % (landed[0], landed[1], text.splitlines()[0][:300] if text else "?"), file=sys.stderr) return if created_remedy: _duckdb_die(exc, remedy=created_remedy, committed=False, table_created=True, rows_written=0, outcome="unknown", current_snapshot_id=now.get("current_snapshot_id")) _duckdb_die(exc, committed=False, current_snapshot_id=now.get("current_snapshot_id")) ns_name = dict(urllib.parse.parse_qsl(q)) die_json("import_outcome_unknown", "DuckDB failed during the commit and the table could not be read back (HTTP %s): " "the rows may or may not be in. %s" % (st, text.splitlines()[0][:300] if text else ""), EXIT_SERVER, committed=None, outcome="unknown", duckdb_message=text[:2000], rows_before=before.get("rows"), current_snapshot_id_before=before.get("current_snapshot_id"), remedy="Check before retrying: lhbox table get --catalog %s --namespace %s --name %s; if its current snapshot is " "no longer %s and is an append of these rows, the import committed (a retry would duplicate every row " "with --mode append).%s" % (ns_name.get("catalog"), ns_name.get("namespace"), ns_name.get("name"), before.get("current_snapshot_id"), (" " + created_remedy) if created_remedy else ""), **({"table_created": True} if created_remedy else {})) # DuckDB type -> Iceberg type, for the schema `table import` sends to POST /v1/tables when the table has to be # created through the API (format version 3). Every column optional: CTAS/INSERT sources have no required flag. _DUCKDB_SCALARS = { "BOOLEAN": "boolean", "TINYINT": "int", "SMALLINT": "int", "INTEGER": "int", "UTINYINT": "int", "USMALLINT": "int", "BIGINT": "long", "UINTEGER": "long", "UBIGINT": "long", "HUGEINT": "decimal(38, 0)", "UHUGEINT": "decimal(38, 0)", "FLOAT": "float", "DOUBLE": "double", "VARCHAR": "string", "JSON": "string", "BLOB": "binary", "BIT": "binary", "DATE": "date", "TIME": "time", "TIMESTAMP": "timestamp", "TIMESTAMP_S": "timestamp", "TIMESTAMP_MS": "timestamp", "TIMESTAMP WITH TIME ZONE": "timestamptz", "UUID": "uuid", } def _split_top_level(text): """'a INTEGER, b STRUCT(x INTEGER, y VARCHAR)' -> ['a INTEGER', 'b STRUCT(x INTEGER, y VARCHAR)'].""" parts, depth, cur, quote = [], 0, "", None for ch in text: if quote: cur += ch if ch == quote: quote = None continue if ch in "\"'": quote = ch elif ch == "(": depth += 1 elif ch == ")": depth -= 1 elif ch == "," and depth == 0: parts.append(cur.strip()) cur = "" continue cur += ch if cur.strip(): parts.append(cur.strip()) return parts def _projjson_authority(obj): """'AUTHORITY:CODE' of a PROJJSON object: its `id`, else its first `ids` entry, else -- for a BoundCRS, whose coordinates are in its source CRS (the bound transformation to WGS 84 is metadata, not another CRS) -- the source CRS's. None when none of them names an authority.""" if not isinstance(obj, dict): return None ident = obj.get("id") or next(iter(obj.get("ids") or []), None) or {} if isinstance(ident, dict) and ident.get("authority") and ident.get("code") is not None: return "%s:%s" % (ident["authority"], ident["code"]) if obj.get("type") == "BoundCRS": return _projjson_authority(obj.get("source_crs")) return None def crs_from_duckdb(crs_text): """The CRS of a GEOMETRY/GEOGRAPHY type as DESCRIBE prints it -> (identifier, projjson). DuckDB 1.5.5 prints a GeoParquet CRS as 'EPSG:25830' when its PROJJSON has a top-level `id`, and the WHOLE PROJJSON otherwise (an `ids` array, a BoundCRS, no id at all; measured 2026-09-28). identifier: 'AUTHORITY:CODE' (_projjson_authority; the rule crs_identifier applies to geo.crs), the text itself when it is not PROJJSON, None when the PROJJSON names no authority. projjson: the canonical PROJJSON text when there is one, else None.""" t = (crs_text or "").strip() if not t.startswith("{"): return t, None try: obj = json.loads(t) except ValueError: return t, None if not isinstance(obj, dict): return t, None return _projjson_authority(obj), json.dumps(obj, separators=(",", ":"), sort_keys=True) class GeometryCRSUnsupported(ValueError): """A geometry CRS with no authority code: Iceberg's only other spelling, `projjson:
`, is accepted by the catalog but DuckDB 1.5.5 cannot create a GEOMETRY of that type ("Encountered unrecognized coordinate system 'projjson:...'", with or without spatial; measured 2026-09-28), so such a table could never be written.""" def _geo_type_crs(kind, crs_text): """The Iceberg `geometry(...)`/`geography(...)` for one DuckDB CRS: the authority code (a type string the catalog accepts; the verbatim PROJJSON answered 400 "Invalid request body", the Portolan import of 2026-09-28). A PROJJSON naming no authority -> GeometryCRSUnsupported(column type, name of the CRS).""" base = kind.lower() ident, projjson = crs_from_duckdb(crs_text) if ident is None: name = (json.loads(projjson).get("name") if projjson else None) or "a PROJJSON without an authority id" raise GeometryCRSUnsupported("%s()" % (kind, name)) return base if ident.upper() in ("", "OGC:CRS84") else "%s(%s)" % (base, ident) def duckdb_type_to_iceberg(duck_type, next_id, format_version=3): """One DuckDB type string (as DESCRIBE prints it) -> an Iceberg type (a string, or a struct/list/map object with ids from next_id()). GEOMETRY/GEOGRAPHY keep their CRS ('OGC:CRS84', Iceberg's default, is dropped), shortened to AUTHORITY:CODE when DESCRIBE printed a PROJJSON (_geo_type_crs; no authority -> GeometryCRSUnsupported). TIMESTAMP_NS is timestamp_ns in v3 and timestamp in v2. Unknown -> ValueError naming the type.""" t = duck_type.strip() u = t.upper() if u.endswith("[]"): return {"type": "list", "element-id": next_id(), "element-required": False, "element": duckdb_type_to_iceberg(t[:-2], next_id, format_version)} m = re.match(r"^(STRUCT|MAP|DECIMAL|GEOMETRY|GEOGRAPHY|ENUM)\s*\((.*)\)$", t, re.S | re.I) if m: kind, inner = m.group(1).upper(), m.group(2) if kind == "STRUCT": fields = [] for item in _split_top_level(inner): name, _, ftype = item.strip().partition(" ") if name.startswith('"') and name.endswith('"'): name = name[1:-1].replace('""', '"') fields.append({"id": next_id(), "name": name, "required": False, "type": duckdb_type_to_iceberg(ftype, next_id, format_version)}) return {"type": "struct", "fields": fields} if kind == "MAP": k, v = _split_top_level(inner) return {"type": "map", "key-id": next_id(), "key": duckdb_type_to_iceberg(k, next_id, format_version), "value-id": next_id(), "value-required": False, "value": duckdb_type_to_iceberg(v, next_id, format_version)} if kind == "DECIMAL": p, s = [x.strip() for x in inner.split(",")] return "decimal(%s, %s)" % (p, s) if kind == "ENUM": return "string" crs = inner.strip() if len(crs) >= 2 and crs[0] == crs[-1] and crs[0] in "'\"": crs = crs[1:-1].replace(crs[0] * 2, crs[0]) # a SQL string literal: '' inside is one quote return _geo_type_crs(kind, crs) if u in ("GEOMETRY", "GEOGRAPHY"): return u.lower() if u == "TIMESTAMP_NS": return "timestamp_ns" if format_version >= 3 else "timestamp" if u in _DUCKDB_SCALARS: return _DUCKDB_SCALARS[u] raise ValueError(t) def schema_from_describe(describe_rows, format_version=3): """DESCRIBE rows ([{column_name, column_type, …}]) -> an Iceberg struct schema with sequential ids. Raises ValueError(column, type) for a type Iceberg has no equivalent of (GeometryCRSUnsupported for a geometry whose CRS names no authority).""" counter = [0] def next_id(): counter[0] += 1 return counter[0] fields = [] for r in describe_rows: fid = next_id() try: typ = duckdb_type_to_iceberg(r["column_type"], next_id, format_version) except GeometryCRSUnsupported as e: raise GeometryCRSUnsupported(r["column_name"], str(e)) except ValueError as e: raise ValueError(r["column_name"], str(e)) fields.append({"id": fid, "name": r["column_name"], "required": False, "type": typ}) return {"type": "struct", "schema-id": 0, "fields": fields} def _is_geometry_type(duck_type): return duck_type.strip().upper().split("(", 1)[0] in ("GEOMETRY", "GEOGRAPHY") def _geo_crs_of_duckdb_type(duck_type, kinds=("GEOMETRY",)): """'GEOMETRY(\'EPSG:25830\')' -> 'EPSG:25830'; 'GEOMETRY' -> ''; not one of `kinds` -> None.""" m = re.match(r"^(%s)\s*(?:\((.*)\))?$" % "|".join(kinds), (duck_type or "").strip(), re.S | re.I) if not m: return None crs = (m.group(2) or "").strip() if len(crs) >= 2 and crs[0] == crs[-1] and crs[0] in "'\"": crs = crs[1:-1].replace(crs[0] * 2, crs[0]) return crs def _same_crs(a, b): """Two CRS spellings for the same identifier ('' and OGC:CRS84 are Iceberg's default; an AUTHORITY:CODE compares case-insensitively: epsg:25830 is EPSG:25830).""" norm = lambda x: "OGC:CRS84" if (x or "").upper() in ("", "OGC:CRS84") else x.upper() # noqa: E731 return a is not None and b is not None and norm(a) == norm(b) def _geo_crs_of_iceberg_type(iceberg_type): """'geometry(EPSG:25830)' / 'geography(EPSG:4326, spherical)' -> 'EPSG:25830' / 'EPSG:4326'; a bare type -> ''; anything else (None, not a geometry) -> ''.""" m = re.match(r"^(?:geometry|geography)(?:\((.*)\))?$", iceberg_type.strip(), re.I) if isinstance(iceberg_type, str) else None return (m.group(1) or "").split(",")[0].strip() if m else "" def geometry_select_expr(column, source_type, target_type): """The SELECT expression that writes the files' GEOMETRY column `column` into a v3 table column of Iceberg type `target_type` ('geometry(EPSG:25830)'). DuckDB compares CRSs as TEXT: a GeoParquet whose PROJJSON it prints in full cannot be cast to GEOMETRY('EPSG:25830') even when both are EPSG:25830 ("Cannot cast GEOMETRY with CRS ... to GEOMETRY with different CRS", measured with DuckDB 1.5.5, 2026-09-28), while a cast through plain GEOMETRY (no CRS) and then to the target is accepted. That re-typing happens ONLY when the source CRS names the same identifier as the target's (crs_from_duckdb): a genuinely different CRS is left to DuckDB, which refuses it, so no coordinates are ever relabelled. Anything else -> the bare column.""" ident = sql_ident(column) m = re.match(r"^geometry(?:\((.*)\))?$", (target_type or "").strip() if isinstance(target_type, str) else "", re.I) src = _geo_crs_of_duckdb_type(source_type) if not m or src is None: return ident target_crs = (m.group(1) or "").strip() if target_crs.lower().startswith("projjson:"): return ident src_ident, _ = crs_from_duckdb(src) if src == target_crs or not _same_crs(src_ident, target_crs): return ident target = "GEOMETRY" if _same_crs(target_crs, "") else "GEOMETRY(%s)" % sql_str(target_crs) return "CAST(CAST(%s AS GEOMETRY) AS %s) AS %s" % (ident, target, ident) def _is_temporal_type(duck_type): """DATE or any TIMESTAMP spelling: the kind of column rows are ordered by when nobody names one.""" u = duck_type.strip().upper() return u == "DATE" or u.startswith("TIMESTAMP") # The layout `table import` writes (research/30-cost-comparison.md §5d, measured 2026-09-23; the public page is # platform/docs/performance.md). A query skips a data file when the file is LARGE and SORTED by the column it filters # on: DuckDB 1.5.5's Iceberg writer emits ~7 MB files by default (342 for 60 M rows; a full scan 5x slower than over # 18 files of ~120 MB) and, with `preserve_insertion_order` off, every file spans the whole range. So: the Iceberg # table property write.target-file-size-bytes = 128 MiB goes on the table BEFORE its first row (CALL # set_iceberg_table_properties on a table DuckDB creates -- never ALTER TABLE … SET, which stores a mis-named property # the writer ignores; the property in POST /v1/tables on one the API creates, where the control plane defaults it # anyway), and the INSERT carries ORDER BY with preserve_insertion_order on. # And the codec: DuckDB's Iceberg writer defaults to SNAPPY, which hardly compresses coordinates (a 5,210-polygon table: # 722 MB SNAPPY against ~590 MB ZSTD, research/54) and honours write.parquet.compression-codec when the table carries it # before the INSERT (measured with DuckDB 1.5.6, 2026-10-02). ZSTD is Iceberg's own default and every engine reads it. TARGET_FILE_SIZE_PROPERTY = "write.target-file-size-bytes" TARGET_FILE_SIZE_BYTES = "134217728" CODEC_PROPERTY = "write.parquet.compression-codec" LAYOUT_PROPERTIES = {TARGET_FILE_SIZE_PROPERTY: TARGET_FILE_SIZE_BYTES, CODEC_PROPERTY: "zstd"} PRESERVE_ORDER_SQL = "SET preserve_insertion_order = true;" # DuckDB 1.5's switch for a partitioned table with a target file size (#3008); 2.0 has no such setting (it refuses the SET) IGNORE_PARTITIONED_FILE_SIZE_SQL = "SET ignore_target_file_size_for_partitioned_tables = true;" # TEMPORARY: the spatial layout of a geometry import (research/49a §5, measured 2026-09-29 with DuckDB 1.5.6). Each piece # works around a DuckDB gap and goes when that gap closes; the import report says so (`spatial_layout.temporary`). # * (Not a workaround: DuckDB prunes files by the manifest's geometry bounds and row groups by the native statistics # for `geometry && `, never for ST_Intersects alone -- research/49a §8. The docs say to write spatial filters # as `geometry && AND ST_Intersects(geometry, )`; CLI 0.4.1's --bbox-columns was dropped in 0.4.2.) # * Its parallel Iceberg write interleaves rows between files even under ORDER BY, so a Hilbert order survives only a # single-threaded write (SET threads = 1); remove when parallel writes keep ORDER BY across files. # * Its default row groups are 122,880 rows (~80 MB); write.parquet.row-group-limit is ignored and # write.parquet.row-group-size-bytes is refused while insertion order is preserved -- and, left on the table, it makes # every plain DuckDB INSERT fail ("ROW_GROUP_SIZE_BYTES does not work while preserving insertion order"). So the import # sets it for its own INSERT (with preserve_insertion_order off; one thread keeps the order) and removes it after. # The Hilbert order itself is NOT temporary: skipping data needs clustered rows in any engine. Where it should live for # tables agents keep appending to (sorted maintenance, "liquid clustering") is future research (49a §6). SPATIAL_ROW_GROUP_PROPERTY = "write.parquet.row-group-size-bytes" SPATIAL_ROW_GROUP_BYTES = "8388608" SPATIAL_SESSION_SQL = ["SET threads = 1;", "SET preserve_insertion_order = false;"] BBOX_COLUMNS = ("bbox_xmin", "bbox_ymin", "bbox_xmax", "bbox_ymax") BBOX_FUNCTIONS = ("ST_XMin", "ST_YMin", "ST_XMax", "ST_YMax") SOURCE_ALIAS = "_src" SPATIAL_LAYOUT_NOTE = ("temporary DuckDB 1.5 workarounds: one writer thread keeps the order across files, " "8 MB row groups for the import's own INSERT (the property is removed after it); the Hilbert order " "stays. Filter with `geometry && AND ST_Intersects(...)`: DuckDB skips data for && only") def default_order_column(describe_rows): """The first DATE/TIMESTAMP column of DESCRIBE's rows, or None.""" for r in describe_rows: if _is_temporal_type(r["column_type"]): return r["column_name"] return None def primary_geometry_column(geometry_cols, geo_props): """The column a spatial order and bbox columns follow: GeoParquet's primary_column when it is a geometry column of the files, else the first geometry column, else None.""" primary = (geo_props or {}).get("geo.primary_column") if primary in geometry_cols: return primary return geometry_cols[0] if geometry_cols else None def hilbert_extent_expr(column, source, geo_props): """The BOX_2D ST_Hilbert orders within: the files' GeoParquet bbox of `column` when they carry one (no extra pass over the data), else one aggregate over the files. Both are in the column's own CRS, as the coordinates are.""" try: bbox = json.loads((geo_props or {}).get("geo.columns") or "{}")[column]["bbox"] except (KeyError, TypeError, ValueError): bbox = None if isinstance(bbox, list) and len(bbox) in (4, 6) and all(isinstance(v, (int, float)) for v in bbox): half = len(bbox) // 2 xmin, ymin, xmax, ymax = bbox[0], bbox[1], bbox[half], bbox[half + 1] return "{'min_x': %r, 'min_y': %r, 'max_x': %r, 'max_y': %r}::BOX_2D" % (float(xmin), float(ymin), float(xmax), float(ymax)) return "(SELECT ST_Extent(ST_Extent_Agg(%s)) FROM %s)" % (sql_ident(column), source) def layout_properties_call(alias, namespace, name, properties=None): """CALL set_iceberg_table_properties('', {...}) -- the dotted identifier as a string.""" pairs = ", ".join("%s: %s" % (sql_str(k), sql_str(v)) for k, v in (properties or LAYOUT_PROPERTIES).items()) return "CALL set_iceberg_table_properties(%s, {%s});" % (sql_str("%s.%s.%s" % (alias, namespace, name)), pairs) # Iceberg has no unsigned integers and no 128-bit one, and DuckDB's Iceberg writer refuses them ("Column type UBIGINT is # not a valid Iceberg Type"; feedback 2026-10-16: a producer's id column was UBIGINT). The import writes # each as the type the schema already maps it to (_DUCKDB_SCALARS), nested ones too (UBIGINT[], STRUCT(id UBIGINT)); a # value that does not fit (a UBIGINT above 2^63-1, a 128-bit value of 39 digits) fails the cast instead of wrapping. _UNSIGNED_CASTS = {"UTINYINT": "INTEGER", "USMALLINT": "INTEGER", "UINTEGER": "BIGINT", "UBIGINT": "BIGINT", "UHUGEINT": "DECIMAL(38, 0)", "HUGEINT": "DECIMAL(38, 0)"} # a TYPE token ends where a type ends (",", ")", "[" or the end); a STRUCT field name is followed by its type instead _UNSIGNED_RE = re.compile(r"\b(%s)\b(?=\s*(?:[,)\[]|$))" % "|".join(sorted(_UNSIGNED_CASTS, key=len, reverse=True)), re.I) def unsigned_cast(column_type): """The DuckDB type a column holding an unsigned or 128-bit integer is written as (at any depth), or None. Quoted names, field names and ENUM labels are never rewritten (high review of #1512).""" t = (column_type or "").strip() if _is_geometry_type(t) or re.match(r"^ENUM\s*\(", t, re.I): return None parts = re.split(r'("(?:[^"]|"")*"|\'(?:[^\']|\'\')*\')', t) # odd items: quoted, left as they are out = [p if i % 2 else _UNSIGNED_RE.sub(lambda m: _UNSIGNED_CASTS[m.group(1).upper()], p) for i, p in enumerate(parts)] new = "".join(out) return new if new != t else None def duckdb_column_def(describe_row, format_version=2): """One column of the CREATE TABLE DuckDB runs against the catalog: the type as DESCRIBE printed it, except a geometry below format version 3 (BLOB: the table holds WKB), an ENUM (VARCHAR: Iceberg has no enum) and an unsigned integer (its signed type, _UNSIGNED_CASTS).""" t = describe_row["column_type"].strip() if _is_geometry_type(t) and format_version < 3: typ = "BLOB" elif re.match(r"^ENUM\s*\(", t, re.I): typ = "VARCHAR" elif unsigned_cast(t): typ = unsigned_cast(t) else: typ = t return "%s %s" % (sql_ident(describe_row["column_name"]), typ) # GeoParquet -> table properties. Until Iceberg v3 geometry is readable by every engine, the `geo` metadata of an # imported GeoParquet lives in these properties (the convention is documented in platform/docs/import-parquet.md # and docs/engines): DuckDB spatial can rebuild the GeoParquet from them on export. def crs_identifier(crs): """A PROJJSON object -> 'EPSG:4326' when it carries an authority id, else the PROJJSON text; a string as given; absent -> 'OGC:CRS84' (the GeoParquet default).""" if crs is None: return "OGC:CRS84" if isinstance(crs, str): return crs if isinstance(crs, dict): ident = crs.get("id") or {} if ident.get("authority") and ident.get("code") is not None: return "%s:%s" % (ident["authority"], ident["code"]) return json.dumps(crs, separators=(",", ":"), sort_keys=True) return str(crs) def geoparquet_properties(geo_by_file): """{file: } of the files that carry it -> the geo.* table properties, or {} when none does. Columns are merged across files: bbox to the union, geometry_types to the union, the rest from the first file. geo.crs is the primary column's CRS as an identifier; geo.crs.projjson keeps the full PROJJSON when the file had one.""" metas = [m for m in geo_by_file.values() if isinstance(m, dict) and m.get("columns")] if not metas: return {} first = metas[0] columns = {} for m in metas: for name, col in (m.get("columns") or {}).items(): if name not in columns: columns[name] = dict(col) continue have = columns[name] if col.get("bbox") and have.get("bbox") and len(col["bbox"]) == len(have["bbox"]): half = len(col["bbox"]) // 2 have["bbox"] = [min(a, b) for a, b in zip(have["bbox"][:half], col["bbox"][:half])] + \ [max(a, b) for a, b in zip(have["bbox"][half:], col["bbox"][half:])] if col.get("geometry_types"): have["geometry_types"] = sorted(set(have.get("geometry_types") or []) | set(col["geometry_types"])) primary = first.get("primary_column") or next(iter(columns)) pcol = columns.get(primary) or {} props = { "geo.encoding": pcol.get("encoding") or "WKB", "geo.primary_column": primary, "geo.crs": crs_identifier(pcol.get("crs")), "geo.columns": json.dumps(columns, separators=(",", ":"), sort_keys=True), } if first.get("version"): props["geo.version"] = str(first["version"]) if isinstance(pcol.get("crs"), dict): props["geo.crs.projjson"] = json.dumps(pcol["crs"], separators=(",", ":"), sort_keys=True) return props def _read_geo_metadata(engine, files): """The 'geo' key of every file's Parquet key/value metadata, parsed -> {file: dict}.""" rows = engine.run("SELECT file_name, decode(value) AS geo FROM parquet_kv_metadata([%s]) WHERE decode(key) = 'geo'" % ", ".join(sql_str(f) for f in files)) out = {} for r in rows: try: out[r["file_name"]] = json.loads(r["geo"]) except (TypeError, ValueError): continue return out def _bytes_of(files): total, known = 0, 0 for f in files: if not f.startswith(REMOTE_SCHEMES): try: total += os.path.getsize(f) known += 1 except OSError: pass return total if known == len(files) else None def _import_table_ref(args): """`table import [catalog.]ns.t FILE…` (the one-table positional, convention 1) or the older `table import FILE… --namespace ns --name t`. argparse hands the first word to the optional table positional either way: with the old flags given it is the first FILE again; without them it must be the table, and a word that looks like a file is refused rather than read as namespace 'data/x' and table 'parquet'.""" ref = getattr(args, "table_ref", None) if ref and (getattr(args, "namespace", None) or getattr(args, "name", None)): args.sources = [ref] + list(args.sources) args.table_ref = None elif ref and (os.path.exists(ref) or any(c in ref for c in "/*?[") or "://" in ref or re.search(r"\.(parquet|csv|tsv|gz)$", ref, re.I)): die("Name the table first: lhbox table import [catalog.]namespace.table %s … (%r looks like a file)." % (ref, ref), EXIT_USAGE) args.namespace, args.name = _table_ref(args) # --row-group-rows: a table of few, large rows (e.g. an image tile per row) needs small row groups, or a point query # downloads the whole file (43 MiB for one row of a raster table; research/90 §3). Every DuckDB write path checks the row-group # size once per 2,048-row chunk, so DuckDB cannot write them. The runner reads the import's own SELECT (casts and ORDER BY # included) from DuckDB (memory capped, the sort spills to a temp directory) a batch at a time, writes the Parquet files # itself with pyarrow (N rows per row group, a new file once the bytes actually written reach the target; no min/max on # binary columns, whose statistics would fill the footer every point query reads), uploads each under the table's data/ # as it closes, and registers them all with ONE PyIceberg add_files in ONE transaction (the table's creation, or the # properties on an append, included): one commit, one manifest, the files' column bounds in it (founder, 2026-10-19). # A failure before the commit deletes the files this run uploaded (best effort) and says so. ROW_GROUP_LIMIT_PROPERTY = "write.parquet.row-group-limit" PYICEBERG_MIN = (0, 12) # format-version 3 tables: PyIceberg 0.12 writes no v3 snapshot and cannot load a geometry column with a CRS of its own, so # add-files talks to the REST catalog itself and builds the commit (manifests with row lineage) with lakehousebox-iceberg-core, # a build of iceberg-rust's Python bindings carrying apache/iceberg-rust#3641-#3643 (PLAN: back to upstream once released) ICEBERG_CORE_DIST = "lakehousebox-iceberg-core" ICEBERG_CORE_MIN = (0, 1) ICEBERG_CORE_FIND_LINKS = "https://github.com/lakehousebox/lakehousebox/releases/expanded_assets/iceberg-core-v0.1.0" ADD_FILES_V3_COMMIT_TRIES = 3 # a commit another writer beat (409) is built again on the fresh table PYICEBERG_BATCH_ROWS = 256 # compressed bytes per data file on this path: every point query reads the footer of each file it touches, ~1 KB per row # group, so small files (Iberia at 1 row per group, 2026-10-19: 128 MB files -> 2.4 MiB per cold point, all footer) ROW_GROUP_FILE_BYTES = 16 << 20 ROW_GROUP_MEMORY_LIMIT = "2GB" # DuckDB's own cap in the runner # DuckDB's sort of wide BLOB rows does not spill (Iberia's 3.5 GB of tiles: out of memory at 1.8 GiB under a 2 GB cap, # 2026-10-19), so an ordered import is sorted in key ranges of about this many uncompressed bytes, one after the other: # each range sorted, the ranges in order = one ordered stream in bounded memory ROW_GROUP_RANGE_BYTES = 400 << 20 _PYICEBERG_PROBE = "\n".join([ "import json, sys", "out = {}", "for m in ('duckdb', 'pyarrow', 'pyiceberg'):", " try:", " out[m] = __import__(m).__version__", " except Exception:", " out[m] = None", "try:", " import importlib.metadata, lhbox_iceberg_core", " out['lhbox_iceberg_core'] = importlib.metadata.version(%r)" % ICEBERG_CORE_DIST, "except Exception:", " out['lhbox_iceberg_core'] = None", "sys.stdout.write('\\n' + %r + json.dumps(out) + '\\n')" % _PY_ANSWER, ]) _PYICEBERG_RUNNER = r""" import json, os, resource, shutil, sys, tempfile, uuid import duckdb import pyarrow as pa import pyarrow.parquet as pq from pyarrow import fs as pafs from pyiceberg.catalog.rest import RestCatalog MARK = "@@ANSWER@@" def answer(obj): sys.stdout.write("\n" + MARK + json.dumps(obj, default=str) + "\n") sys.stdout.flush() req = json.load(sys.stdin) c = req["catalog"] scheme, host = c["s3_endpoint"].split("://", 1) cat = RestCatalog(name="lhbox", uri=c["uri"], warehouse=c["warehouse"], credential=c["key_id"] + ":" + c["secret"], **{"s3.endpoint": c["s3_endpoint"], "s3.path-style-access": "true", "s3.region": "us-east-1", "s3.access-key-id": c["key_id"], "s3.secret-access-key": c["secret"]}) s3 = pafs.S3FileSystem(access_key=c["key_id"], secret_key=c["secret"], endpoint_override=host.rstrip("/"), scheme=scheme, region="us-east-1") tmp = tempfile.mkdtemp(prefix="lhbox-import-") con = duckdb.connect() def batches(sql, params=()): rel = con.execute(sql, list(params)) return rel.to_arrow_reader(req["batch_rows"]) if hasattr(rel, "to_arrow_reader") else rel.fetch_record_batch(req["batch_rows"]) def ident_sql(name): return '"' + name.replace('"', '""') + '"' proj, oc = req["projection"], req["order_column"] ident = (req["namespace"], req["name"]) written, stage, rows, ranges, nulls = [], "write", 0, 1, [] try: for st in ["SET enable_progress_bar = false", "SET preserve_insertion_order = true", "SET memory_limit = '%s'" % req["memory_limit"], "SET temp_directory = '%s'" % tmp]: con.execute(st) schema = batches("SELECT * FROM (%s) LIMIT 0" % proj).schema queries = [("SELECT * FROM (%s)" % proj + (" ORDER BY %s" % ident_sql(oc) if oc else ""), [])] if oc and req["parquet_files"]: size = con.execute("SELECT sum(total_uncompressed_size) FROM parquet_metadata(?)", [req["parquet_files"]]).fetchone()[0] or 0 ranges = max(1, -(-int(size) // req["range_bytes"])) if ranges > 1: cuts = con.execute("SELECT quantile_disc(%s, ?) FROM (%s)" % (ident_sql(oc), proj), [[i / ranges for i in range(1, ranges)]]).fetchone()[0] or [] cuts = sorted(set(v for v in cuts if v is not None)) ranges = 1 if not cuts else ranges # one key (or all NULL): no cut to make, one sorted pass if ranges > 1: o, queries, lo = ident_sql(oc), [], None for hi in cuts + [None]: conds, params = [], [] if lo is not None: conds.append("%s > ?" % o); params.append(lo) if hi is not None: conds.append("%s <= ?" % o); params.append(hi) queries.append(("SELECT * FROM (%s) WHERE %s ORDER BY %s" % (proj, " AND ".join(conds), o), params)) lo = hi queries.append(("SELECT * FROM (%s) WHERE %s IS NULL" % (proj, o), [])) ranges = len(queries) if req["mode"] == "create": cat.create_namespace_if_not_exists(req["namespace"]) tx = cat.create_table_transaction(ident, schema=schema, properties=req["properties"]) else: tx = cat.load_table(ident).transaction() if req["properties"]: tx.set_properties(req["properties"]) # a column the files lack is projected as NULL, which DuckDB types as Arrow null: PyIceberg refuses that type at # add_files, after every file was written. It takes the table's own type (no field ids: add_files refuses them) def plain(t): if pa.types.is_struct(t): return pa.struct([pa.field(f.name, plain(f.type)) for f in t]) if pa.types.is_large_list(t): return pa.large_list(plain(t.value_type)) if pa.types.is_list(t): return pa.list_(plain(t.value_type)) if pa.types.is_map(t): return pa.map_(plain(t.key_type), plain(t.item_type)) return t table_arrow = tx.table_metadata.schema().as_arrow() nulls = [i for i, f in enumerate(schema) if pa.types.is_null(f.type) and f.name in table_arrow.names] required = [schema.field(i).name for i in nulls if not table_arrow.field(schema.field(i).name).nullable] if required: # refused before any file is written, not at add_files raise ValueError("the table requires %s, which the files lack" % ", ".join(required)) if nulls: schema = pa.schema([pa.field(f.name, plain(table_arrow.field(f.name).type)) if i in nulls else f for i, f in enumerate(schema)]) loc = tx.table_metadata.location.rstrip("/") stats = [f.name for f in schema if not (pa.types.is_binary(f.type) or pa.types.is_large_binary(f.type))] writer = sink = None for sql, params in queries: for batch in batches(sql, params): if nulls: batch = pa.RecordBatch.from_arrays([pa.nulls(batch.num_rows, schema.field(i).type) if i in nulls else batch.column(i) for i in range(batch.num_columns)], schema=schema) if writer is None: path = "%s/data/%s.parquet" % (loc, uuid.uuid4()) written.append(path) sink = s3.open_output_stream(path.split("://", 1)[1]) writer = pq.ParquetWriter(sink, schema, compression="zstd", write_statistics=stats or False) writer.write_batch(batch, row_group_size=req["row_group_rows"]) rows += batch.num_rows if sink.tell() >= req["target_bytes"]: writer.close(); sink.close(); writer = None if writer is not None: writer.close(); sink.close() stage = "register" if written: tx.add_files(written) stage = "commit" tx.commit_transaction() except Exception as exc: out = {"error": "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0][:500] if str(exc) else ""), "stage": stage, "files": len(written)} if stage != "commit": left = [] for p in written: try: s3.delete_file(p.split("://", 1)[1]) except Exception: left.append(p) out.update(deleted=len(written) - len(left), left=left) answer(out) sys.exit(1) finally: shutil.rmtree(tmp, ignore_errors=True) answer({"committed": True, "files": len(written), "rows": rows, "ranges": ranges, "peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * (1 if sys.platform == "darwin" else 1024)}) """.replace("@@ANSWER@@", _PY_ANSWER) # `table add-files` (#1659, founder 2026-10-20, design A): finished Parquet files registered AS THEY ARE -- the producer # lays the data out (row groups, order, compression) with its own tools and stages the files in the catalog's files with # `lhbox file put` # (the one upload path); add-files copies them SERVER-SIDE into the table's data/ (CopyObject, UploadPartCopy above # copy_max: no byte passes through this machine), registers them all in ONE add_files commit, then deletes the staged # copies (--keep-staged keeps them). Only the footers are read (range GETs of the staged objects): the schema (the same # in every file, and fitting the table on an append), field ids (PyIceberg's add_files maps columns by name and refuses # files that carry Iceberg field ids), and generic layout warnings, never acted on. Measured before it was built # (2026-10-20, jatorre/analytics): the catalog's key pair may copy from its files bucket into /
/data/ of its # table bucket (CopyObject of 629 MB in 0.96 s; UploadPartCopy in 64 MiB parts in 3.1 s), the table bucket refuses the # same copy to any other key (403), and every copy read back whole after its source was deleted (sha256 equal). ADD_FILES_ROW_GROUP_WARN_BYTES = 64 << 20 # a point read downloads whole row groups: above this per row group, a warning # ... and above this one when its rows are wide (few, large rows, e.g. an image tile per row; measured 2026-10-20 on a # raster file written as one 16.7 MB row group of 3,073 rows, 5.4 KB each on average: 15.8 MiB downloaded for one cold # point read) ADD_FILES_WIDE_ROW_GROUP_BYTES = 4 << 20 ADD_FILES_WIDE_ROW_BYTES = 2 << 10 ADD_FILES_COPY_MAX_BYTES = 5 << 30 # S3's limit for one CopyObject; a larger file is copied in parts ADD_FILES_COPY_PART_BYTES = 512 << 20 # UploadPartCopy's part size (10,000 parts: up to 5 TB) ADD_FILES_HTTP_TIMEOUT = 900 # a server-side copy of a large part takes a while; nothing streams meanwhile _ADD_FILES_RUNNER = r""" import json, os, re, resource, sys, time, uuid, urllib.error, urllib.parse, urllib.request import pyarrow as pa import pyarrow.parquet as pq from pyarrow import fs as pafs MARK = "@@ANSWER@@" def answer(obj): sys.stdout.write("\n" + MARK + json.dumps(obj, default=str) + "\n") sys.stdout.flush() def refuse(code, message, **detail): answer(dict(refused=code, message=message, stage="inspect", **detail)) sys.exit(1) def fields(schema): return ["%s %s" % (f.name, f.type) for f in schema] def first_line(exc): text = str(exc).strip() return text.splitlines()[0][:300] if text else type(exc).__name__ @@SIGV4@@ req = json.load(sys.stdin) c = req["catalog"] endpoint = c["s3_endpoint"].rstrip("/") scheme, host = endpoint.split("://", 1) s3 = pafs.S3FileSystem(access_key=c["key_id"], secret_key=c["secret"], endpoint_override=host, scheme=scheme, region="us-east-1") fbucket, staged, sorted_by = req["files_bucket"], req["staged"], req.get("sorted_by") def q(text): return urllib.parse.quote(text, safe="-_.~") def s3_call(method, bucket, key, query="", data=b"", extra=None): url = "%s/%s/%s%s" % (endpoint, bucket, urllib.parse.quote(key, safe="/-_.~"), ("?" + query) if query else "") rq = urllib.request.Request(url, data=data if method in ("PUT", "POST") else None, method=method) for k, v in _sigv4_headers(method, url, c["key_id"], c["secret"], payload=data, extra=extra).items(): rq.add_header(k, v) try: with urllib.request.urlopen(rq, timeout=req["timeout"]) as r: status, body = r.status, r.read() except urllib.error.HTTPError as e: status, body = e.code, e.read() text = body.decode("utf-8", "replace") if status >= 300 or "" in text: # a copy can answer 200 with an error in its body code, msg = re.search(r"([^<]*)", text), re.search(r"([^<]*)", text) raise StoreError("%s %s: HTTP %d %s: %s" % (method, key, status, code.group(1) if code else "", msg.group(1) if msg else text[:200]), status, code.group(1) if code else "") return text class StoreError(IOError): def __init__(self, message, status, code=""): IOError.__init__(self, message) self.status, self.code = status, code def transient(self): # worth another try: a server error, or one of S3's retryable codes (also in a 200 body); never a refusal return self.status >= 500 or self.code in ("InternalError", "ServiceUnavailable", "SlowDown", "RequestTimeout") def head_size(bucket, key): # an object's size, or None when there is none url = "%s/%s/%s" % (endpoint, bucket, urllib.parse.quote(key, safe="/-_.~")) rq = urllib.request.Request(url, method="HEAD") for k, v in _sigv4_headers("HEAD", url, c["key_id"], c["secret"]).items(): rq.add_header(k, v) try: with urllib.request.urlopen(rq, timeout=req["timeout"]) as r: return int(r.headers.get("Content-Length")) except urllib.error.HTTPError as e: if e.code == 404: return None raise def copy_call(bucket, key, size=None, **kw): # a server-side copy (CopyObject, or UploadPartCopy with its part number: both overwrite, so a retry is safe). The store # answers only when the copy is done, and a copy can outlast the wait while it still completes (#2664: 20-40 MB copies # under load): a failure that is not a refusal (a timeout, a dropped connection, a 5xx) is retried, and a whole-object # copy first looks for its destination, which a copy that went on without us has written whole tries, wait = int(req.get("copy_tries") or 2), float(req.get("copy_wait", 5)) for attempt in range(tries): try: return s3_call("PUT", bucket, key, **kw) except Exception as exc: if (isinstance(exc, StoreError) and not exc.transient()) or attempt + 1 == tries: raise for _ in range(6 if size is not None else 0): time.sleep(wait) try: if head_size(bucket, key) == size: return "" except Exception: pass time.sleep(wait * (attempt + 1)) class CommitConflict(Exception): pass class CommitRejected(Exception): pass class Refused(Exception): def __init__(self, code, message, **detail): Exception.__init__(self, message) self.code, self.message, self.detail = code, message, detail def rest(method, path, body=None, form=None, token=None): # the Iceberg REST catalog, for format-version 3 tables (PyIceberg 0.12 cannot load every v3 table nor write one). # 409: another writer won (CommitConflict); any other 4xx: refused, nothing is in (CommitRejected); 5xx: unknown data = urllib.parse.urlencode(form).encode() if form else (json.dumps(body).encode() if body is not None else None) rq = urllib.request.Request(c["uri"].rstrip("/") + path, data=data, method=method) rq.add_header("Content-Type", "application/x-www-form-urlencoded" if form else "application/json") if token: rq.add_header("Authorization", "Bearer " + token) try: with urllib.request.urlopen(rq, timeout=req["timeout"]) as r: status, text = r.status, r.read().decode("utf-8", "replace") except urllib.error.HTTPError as e: status, text = e.code, e.read().decode("utf-8", "replace") if status == 409: raise CommitConflict(text[:300]) if 400 <= status < 500: raise CommitRejected("%s %s: HTTP %d: %s" % (method, path, status, text[:300])) if status >= 300: raise IOError("%s %s: HTTP %d: %s" % (method, path, status, text[:300])) return json.loads(text) if text.strip() else {} def rest_table(): # -> (REST path of the table, a fresh token, metadata-location, the metadata file's own text) tok = rest("POST", "/v1/oauth/tokens", form={"grant_type": "client_credentials", "client_id": c["key_id"], "client_secret": c["secret"], "scope": "catalog"})["access_token"] conf = rest("GET", "/v1/config?" + urllib.parse.urlencode({"warehouse": c["warehouse"]}), token=tok) prefix = (conf.get("overrides") or {}).get("prefix") or (conf.get("defaults") or {}).get("prefix") path = "/v1/%snamespaces/%s/tables/%s" % (q(prefix) + "/" if prefix else "", q(req["namespace"]), q(req["name"])) loc = rest("GET", path, token=tok)["metadata-location"] with s3.open_input_file(loc.split("://", 1)[1]) as fh: return path, tok, loc, fh.read().decode() def current_fields(meta): return [x for x in meta["schemas"] if x.get("schema-id") == meta.get("current-schema-id")][0]["fields"] def name_mapping(fields_): out = [] for f in fields_: m = {"field-id": f["id"], "names": [f["name"]]} t = f["type"] if isinstance(t, dict): kids = (t.get("fields") or []) if t.get("type") == "struct" else ( [{"id": t["element-id"], "name": "element", "type": t["element"]}] if t.get("type") == "list" else [{"id": t["key-id"], "name": "key", "type": t["key"]}, {"id": t["value-id"], "name": "value", "type": t["value"]}]) if kids: m["fields"] = name_mapping(kids) out.append(m) return out GEO_TYPE = re.compile(r"\s*(geometry|geography)\s*(?:\((.*)\))?\s*$", re.I) def as_binary(t): # the table's types with geometry/geography as binary (their WKB in the files), for PyIceberg 0.12's own schema check if isinstance(t, str): return "binary" if GEO_TYPE.match(t) else t t = dict(t) for k in ("element", "key", "value"): if k in t: t[k] = as_binary(t[k]) if "fields" in t: t["fields"] = [dict(f, type=as_binary(f["type"])) for f in t["fields"]] return t def storage(arrow): # extension types (geoarrow.wkb) as their storage type, no field metadata: what the schema check compares return pa.schema([pa.field(f.name, getattr(f.type, "storage_type", f.type), f.nullable) for f in arrow]) def v3_mismatch(fields_, arrow): # PyIceberg's own rules (what the format-version 2 path applies): by column name, no narrowing, decimals, timestamp # units, required columns, nested types from pyiceberg.schema import Schema from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible try: schema = Schema.model_validate({"type": "struct", "schema-id": 0, "fields": [dict(f, type=as_binary(f["type"])) for f in fields_]}) _check_pyarrow_schema_compatible(schema, storage(arrow), format_version=3) except Exception as exc: return str(exc).strip()[:1500] or type(exc).__name__ return None def table_crs(t): # geometry -> OGC:CRS84 (the spec's default), geometry(EPSG:4326) / geometry('EPSG:4326') -> EPSG:4326. As written, case # and all: DuckDB 1.5 types the column with this text and compares it case-sensitively with the files' CRS (a plain # GEOMETRY column it creates is stored as geometry(ogc:crs84), and then it cannot read a file whose CRS is OGC:CRS84: # "Cannot cast GEOMETRY with CRS 'OGC:CRS84' to GEOMETRY with different CRS 'ogc:crs84'", measured 2026-11-06, #2664) m = GEO_TYPE.match(t) if isinstance(t, str) else None if not m: return None crs = (m.group(2) or "").split(",")[0].strip().strip("'\"") return crs or "OGC:CRS84" def crs_name(crs): # a declared CRS as DuckDB names it: PROJJSON (an object, or its text) -> its top-level id, AUTHORITY:CODE as the id # spells it ({"authority": "EPSG", "code": 4326} -> EPSG:4326, OGC CRS84 -> OGC:CRS84; DuckDB writes every GEOMETRY # CRS this way, GEOPARQUET_VERSION 'V2' included, #2664). Without a top-level id DuckDB types the column with the whole # PROJJSON, which no table type equals: "UNIDENTIFIED PROJJSON". A string is compared as written (case and all: #2703) if crs is None: return None if isinstance(crs, str) and crs.lstrip().startswith("{"): try: crs = json.loads(crs) except ValueError: return "UNIDENTIFIED PROJJSON" if isinstance(crs, dict): i = crs.get("id") if isinstance(i, dict) and i.get("authority") and i.get("code") is not None: return "%s:%s" % (i["authority"], i["code"]) return "UNIDENTIFIED PROJJSON" return str(crs) NOT_NATIVE = object() def parquet_geo_crs(md, column): # a column of Parquet's own GEOMETRY type (pyarrow reads it as plain binary unless an extension is registered): its crs; # None when it declares none (DuckDB reads it without a CRS, whatever GeoParquet metadata the file also has: no claim); # NOT_NATIVE when the column is not of that type pschema = md.schema for k in range(len(pschema)): col = pschema.column(k) if col.path != column: continue try: lt = json.loads(col.logical_type.to_json()) except Exception: return NOT_NATIVE if str(lt.get("Type", "")).lower() not in ("geometry", "geography"): return NOT_NATIVE crs = lt.get("crs") if not crs: # no claim: DuckDB types it GEOMETRY with no CRS (review of #2703) return None if isinstance(crs, str) and crs.startswith("projjson:"): # a key of the file's metadata holds the PROJJSON crs = ((md.metadata or {}).get(crs[len("projjson:"):].encode()) or b"").decode() or crs return crs_name(crs) return NOT_NATIVE def file_crs(schema, column, md=None): # the CRS a file declares for a column, which readers such as DuckDB type the column with. Parquet's GEOMETRY type: its # crs, None when it declares none (DuckDB's GEOPARQUET_VERSION 'V2' file of a plain GEOMETRY also carries GeoParquet # metadata without crs, which DuckDB does not read), read from the Parquet schema. Else pyarrow's geoarrow extension type # or GeoParquet metadata: its crs, OGC:CRS84 when absent, null = no claim. Neither: None (the table's CRS applies). native = parquet_geo_crs(md, column) if md is not None else NOT_NATIVE if native is not NOT_NATIVE: # the Parquet type is what DuckDB reads: GeoParquet metadata is not asked return native f = schema.field(column) if column in schema.names else None if f is not None: meta = f.metadata or {} ext = getattr(f.type, "extension_name", None) or (meta.get(b"ARROW:extension:name") or b"").decode() if ext.startswith("geoarrow."): try: raw = f.type.__arrow_ext_serialize__() if hasattr(f.type, "__arrow_ext_serialize__") else \ meta.get(b"ARROW:extension:metadata", b"") info = json.loads(raw or b"{}") except Exception: info = {} return crs_name(info["crs"]) if "crs" in info else "OGC:CRS84" try: col = json.loads((schema.metadata or {})[b"geo"])["columns"][column] except Exception: return None return crs_name(col["crs"]) if "crs" in col else "OGC:CRS84" def crs_mismatch(fields_): # -> (file, column, file crs, table crs) for the first file whose CRS is not the table column's: registered, it makes # the table unreadable to DuckDB ("Cannot cast GEOMETRY with CRS 'OGC:CRS84' to ... 'EPSG:4326'", measured) geo_cols = {f["name"]: table_crs(f["type"]) for f in fields_ if table_crs(f["type"])} for path, schema, md in file_schemas: for col, want in geo_cols.items(): got = file_crs(schema, col, md) if got is not None and got != want: return path, col, got, want return None def geom_bounds(md, column): # -> (xmin, ymin, xmax, ymax) of every geometry in one file's column, from statistics its writer computed (no data read): # Parquet's geospatial statistics of each row group, else the GeoParquet 1.1 bbox covering columns' min/max. None when a # row group with values has neither: no bound is better than a wrong one (a reader would skip rows that match) leaves = [md.schema.column(k).path for k in range(len(md.schema))] cov = {} try: c = json.loads((md.metadata or {})[b"geo"])["columns"][column]["covering"]["bbox"] cov = {a: leaves.index(".".join(c[a])) for a in ("xmin", "ymin", "xmax", "ymax")} except Exception: cov = {} k = leaves.index(column) if column in leaves else None boxes = [] for i in range(md.num_row_groups): rg = md.row_group(i) if rg.num_rows == 0: continue cc = rg.column(k) if k is not None else None st = cc.statistics if cc is not None and cc.is_stats_set else None if st is not None and st.null_count is not None and st.null_count >= rg.num_rows: continue # only nulls box = None g = cc.geo_statistics if cc is not None and getattr(cc, "is_geo_stats_set", False) else None if g is not None: box = (g.xmin, g.ymin, g.xmax, g.ymax) elif cov: s = {a: rg.column(j).statistics for a, j in cov.items()} if all(x is not None and x.has_min_max for x in s.values()): box = (s["xmin"].min, s["ymin"].min, s["xmax"].max, s["ymax"].max) try: box = tuple(float(v) for v in box) if box is not None else None except (TypeError, ValueError): box = None # wraparound (xmin > xmax), empty or non-finite boxes: not a bound DuckDB can use if box is None or not all(abs(v) != float("inf") and v == v for v in box) or box[0] > box[2] or box[1] > box[3]: return None boxes.append(box) if not boxes: return None return (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)) class Bytes: # PyIceberg's InputFile/OutputFile over this runner's own store calls: a GET through pyarrow's S3, a signed PUT def __init__(self, uri): self.uri, self.buf = uri, None def open(self, seekable=True): import io with s3.open_input_file(self.uri.split("://", 1)[1]) as fh: return io.BytesIO(fh.read()) def create(self, overwrite=False): import io out, uri = io.BytesIO(), self.uri def close(): data = out.getvalue() bucket, key = uri.split("://", 1)[1].split("/", 1) s3_call("PUT", bucket, key, data=data) self.buf = data io.BytesIO.close(out) out.close = close return out def avro_rewrite(src, dest, fix): # an Avro file of the commit (a manifest, a manifest list), read whole, each record passed to fix, written to dest with # the same schema and metadata (format-version, partition spec, codec) -> (records fix changed, dest's length) from pyiceberg.avro.file import AvroFile, AvroOutputFile with AvroFile(Bytes(src)) as f: schema, meta, recs = f.schema, dict(f.header.meta), list(f) name = json.loads(meta.pop("avro.schema"))["name"] changed = sum(1 for r in recs if fix(schema.as_struct(), r)) out = Bytes(dest) with AvroOutputFile(out, schema, name, metadata=meta) as w: w.write_block(recs) return changed, len(out.buf) def at(struct_type, name): return [f.name for f in struct_type.fields].index(name) def with_geom_bounds(body, bounds): # the commit add_files built, with each added file's geometry bounds ({path: {field id: box}}) in its manifest entry, as # the Iceberg v3 spec packs them (x then y, little-endian doubles: the box's lower and upper corners) and as DuckDB # writes them; a reader skips the files a spatial filter's box misses. The manifests this snapshot added and its # manifest list are written again under new names; the commit then names that list. -> (new body, files with bounds) import copy, struct as st body = copy.deepcopy(body) snap = [u for u in body["updates"] if u.get("action") == "add-snapshot"][0]["snapshot"] sid, mlist = snap["snapshot-id"], snap["manifest-list"] meta_dir = mlist.rsplit("/", 1)[0] lengths, n = {}, [0] def fix_entry(t, r): di = at(t, "data_file") dt = t.fields[di].field_type df = r[di] boxes = bounds.get(df[at(dt, "file_path")]) if not boxes: return False li, ui = at(dt, "lower_bounds"), at(dt, "upper_bounds") lo, hi = dict(df[li] or {}), dict(df[ui] or {}) for fid, b in boxes.items(): lo[fid], hi[fid] = st.pack("<2d", b[0], b[1]), st.pack("<2d", b[2], b[3]) df[li], df[ui] = lo, hi n[0] += 1 return True def fix_list(t, r): p = r[at(t, "manifest_path")] if p in lengths: r[at(t, "manifest_path")], r[at(t, "manifest_length")] = lengths[p] return True return False from pyiceberg.avro.file import AvroFile with AvroFile(Bytes(mlist)) as f: t = f.schema.as_struct() mine = [r[at(t, "manifest_path")] for r in f if r[at(t, "added_snapshot_id")] == sid] written = [] try: for m in mine: # only the manifests of this snapshot: never one a table already has dest = "%s/%s-m0.avro" % (meta_dir, uuid.uuid4()) written.append(dest) lengths[m] = (dest, avro_rewrite(m, dest, fix_entry)[1]) dest = "%s/snap-%d-1-%s.avro" % (meta_dir, sid, uuid.uuid4()) written.append(dest) avro_rewrite(mlist, dest, fix_list) except Exception: drop_objects(written) raise drop_objects(mine + [mlist]) # what add_files wrote: replaced, never committed snap["manifest-list"] = dest return body, n[0], written # Parquet footers (Thrift compact protocol): just enough to read FileMetaData into [field id, type, value] triples and # write it back byte for byte, so that one field can be added. DuckDB (1.5.6, 2.0) uses a column chunk's # geospatial_statistics only when the chunk also has a `statistics` struct (TransformColumnStatistics returns early without # one), and pyarrow / Arrow C++ writes GEOMETRY chunks with geospatial_statistics and no statistics: `geom && box` then # skips no row group of such a file (#2664). Adding an empty Statistics fixes it. The data pages, the page indexes and # every offset stay where they are: only the bytes after them (the footer, its length, the magic) change. TC_TRUE, TC_FALSE, TC_BYTE, TC_I16, TC_I32, TC_I64, TC_DOUBLE, TC_BINARY, TC_LIST, TC_SET, TC_MAP, TC_STRUCT = range(1, 13) class ThriftReader: def __init__(self, buf): self.b, self.i = buf, 0 def byte(self): if self.i >= len(self.b): raise ValueError("truncated footer") self.i += 1 return self.b[self.i - 1] def take(self, n): if self.i + n > len(self.b): raise ValueError("truncated footer") self.i += n return self.b[self.i - n:self.i] def varint(self): out = shift = 0 while True: x = self.byte() out |= (x & 0x7F) << shift shift += 7 if not x & 0x80: return out def value(self, t): if t in (TC_TRUE, TC_FALSE): # a struct field's bool is its type nibble return None if t == TC_BYTE: return self.byte() if t in (TC_I16, TC_I32, TC_I64): # the zigzag varint as read: written back the same return self.varint() if t == TC_DOUBLE: return self.take(8) if t == TC_BINARY: return self.take(self.varint()) if t in (TC_LIST, TC_SET): h = self.byte() n, et = h >> 4, h & 15 if n == 15: n = self.varint() return (et, [self.elem(et) for _ in range(n)]) if t == TC_MAP: n = self.varint() kv = self.byte() if n else 0 return (kv, [(self.elem(kv >> 4), self.elem(kv & 15)) for _ in range(n)]) if t == TC_STRUCT: return self.struct() raise ValueError("unknown thrift type %d" % t) def elem(self, t): return self.byte() if t in (TC_TRUE, TC_FALSE) else self.value(t) # a bool in a container is a byte def struct(self): out, last = [], 0 while True: h = self.byte() if h == 0: return out t, d = h & 15, h >> 4 if d: fid = last + d else: z = self.varint() fid = (z >> 1) ^ -(z & 1) out.append([fid, t, self.value(t)]) last = fid def thrift_write(fields_): out = bytearray() def varint(n): while n >= 0x80: out.append((n & 0x7F) | 0x80) n >>= 7 out.append(n) def elem(t, v): if t in (TC_TRUE, TC_FALSE): out.append(v) else: value(t, v) def value(t, v): if t in (TC_TRUE, TC_FALSE): return if t == TC_BYTE: out.append(v) elif t in (TC_I16, TC_I32, TC_I64): varint(v) elif t == TC_DOUBLE: out.extend(v) elif t == TC_BINARY: varint(len(v)) out.extend(v) elif t in (TC_LIST, TC_SET): et, items = v if len(items) < 15: out.append(len(items) << 4 | et) else: out.append(0xF0 | et) varint(len(items)) for x in items: elem(et, x) elif t == TC_MAP: kv, pairs = v varint(len(pairs)) if pairs: out.append(kv) for k, x in pairs: elem(kv >> 4, k) elem(kv & 15, x) else: struct(v) def struct(fs): last = 0 for fid, t, v in fs: if 0 < fid - last <= 15: out.append((fid - last) << 4 | t) else: out.append(t) varint((fid << 1) if fid >= 0 else (-fid << 1) - 1) value(t, v) last = fid out.append(0) struct(fields_) return bytes(out) def tfield(fs, fid): return next((f[2] for f in fs if f[0] == fid), None) def footer_with_statistics(raw): # FileMetaData bytes -> (the same with an empty `statistics` (ColumnMetaData field 12) in every column chunk that has # geospatial_statistics (field 17) and no statistics, how many chunks) -- (None, 0) when none needs it. ValueError when # the footer is not one this writes back exactly, or encrypted: such a file is copied as it is fmd = ThriftReader(raw).struct() if thrift_write(fmd) != raw: raise ValueError("the footer does not read back byte for byte") if tfield(fmd, 8) is not None: # encryption_algorithm: the plaintext footer of an encrypted file raise ValueError("an encrypted file") changed = 0 for rg in (tfield(fmd, 4) or (TC_STRUCT, []))[1]: for cc in (tfield(rg, 1) or (TC_STRUCT, []))[1]: if tfield(cc, 8) is not None or tfield(cc, 9) is not None: raise ValueError("an encrypted column") md = tfield(cc, 3) if md is not None and tfield(md, 17) is not None and tfield(md, 12) is None: md.append([12, TC_STRUCT, []]) md.sort(key=lambda f: f[0]) changed += 1 return (thrift_write(fmd), changed) if changed else (None, 0) def lacks_statistics(md): # a column chunk with geospatial statistics and no Statistics struct: DuckDB never uses its geospatial statistics return any(getattr(md.row_group(i).column(j), "is_geo_stats_set", False) and not md.row_group(i).column(j).is_stats_set for i in range(md.num_row_groups) for j in range(md.num_columns)) def new_tail(obj): # a staged file -> (length of the bytes before its footer, the new footer + length + magic, chunks changed) import io with s3.open_input_file("%s/%s" % (fbucket, obj["key"])) as fh: fh.seek(obj["size"] - 8) end = fh.read(8) flen = int.from_bytes(end[:4], "little") if end[4:] != b"PAR1" or flen + 12 > obj["size"]: raise ValueError("not a plain Parquet footer") fh.seek(obj["size"] - 8 - flen) raw = fh.read(flen) footer, changed = footer_with_statistics(raw) if footer is None: raise ValueError("no column chunk to change") tail = footer + len(footer).to_bytes(4, "little") + b"PAR1" # read back as pyarrow reads it: the same rows, row groups, columns and schema, and no chunk left without statistics old = pq.ParquetFile(io.BytesIO(b"PAR1" + raw + end)).metadata new = pq.ParquetFile(io.BytesIO(b"PAR1" + tail)).metadata if (new.num_rows, new.num_row_groups, new.num_columns) != (old.num_rows, old.num_row_groups, old.num_columns) \ or not new.schema.equals(old.schema) or lacks_statistics(new): raise ValueError("the new footer does not read back as the old one") return obj["size"] - 8 - flen, tail, changed def put_part(bucket, key, n, uid, data): # UploadPart of bytes we have -> its ETag (a response header); a retry overwrites the part url = "%s/%s/%s?partNumber=%d&uploadId=%s" % (endpoint, bucket, urllib.parse.quote(key, safe="/-_.~"), n, q(uid)) for attempt in range(2): rq = urllib.request.Request(url, data=data, method="PUT") for k, v in _sigv4_headers("PUT", url, c["key_id"], c["secret"], payload=data).items(): rq.add_header(k, v) try: with urllib.request.urlopen(rq, timeout=req["timeout"]) as r: return r.headers.get("ETag") except urllib.error.HTTPError as e: if e.code < 500 or attempt: raise StoreError("PUT %s part %d: HTTP %d" % (key, n, e.code), e.code) except Exception: if attempt: raise def copy_with_tail(tbucket, key, source, obj, body_len, tail): # the bytes before the footer copied in the store, the new tail uploaded after them, as one multipart upload (every # part but the last >= 5 MiB); a file whose body is under 5 MiB is read and written whole -> (requests, size, upload id) if body_len < (5 << 20): with s3.open_input_file("%s/%s" % (fbucket, obj["key"])) as fh: body = fh.read(body_len) copy_call(tbucket, key, data=body + tail) return 1, body_len + len(tail) text = s3_call("POST", tbucket, key, query="uploads") uid = re.search(r"([^<]+)", text).group(1) ranges = [[lo, min(lo + req["part_bytes"], body_len)] for lo in range(0, body_len, req["part_bytes"])] if len(ranges) > 1 and ranges[-1][1] - ranges[-1][0] < (5 << 20): last = ranges.pop() # a short last copied part joins the one before it ranges[-1][1] = last[1] parts = [] try: for n, (lo, hi) in enumerate(ranges, 1): t = copy_call(tbucket, key, query="partNumber=%d&uploadId=%s" % (n, q(uid)), extra={"x-amz-copy-source": source, "x-amz-copy-source-range": "bytes=%d-%d" % (lo, hi - 1)}) parts.append((n, re.search(r"([^<]+)", t).group(1))) parts.append((len(parts) + 1, put_part(tbucket, key, len(parts) + 1, uid, tail))) s3_call("POST", tbucket, key, query="uploadId=%s" % q(uid), data=("%s" % "".join("%d%s" % p for p in parts)).encode()) except Exception: try: s3_call("DELETE", tbucket, key, query="uploadId=%s" % q(uid)) except Exception: pass raise return len(parts), body_len + len(tail) def drop_objects(uris): # best effort: files of a commit that will not happen (the store's orphan cleanup is the backstop) for u in uris: try: s3_call("DELETE", *u.split("://", 1)[1].split("/", 1)) except Exception: pass def v3_guard(meta): # every check on the table as it is now: run before the copy, and again on the table each commit is built on fv = int(meta.get("format-version", 2)) if fv != 3: raise Refused("format_version_unsupported", "The table is format-version %d now (it was 3 when add-files started)." % fv, format_version=fv) spec = [x for x in meta.get("partition-specs", []) if x.get("spec-id") == meta.get("default-spec-id")] if spec and spec[0].get("fields"): raise Refused("partitioned_table", "The table is partitioned; add-files registers into unpartitioned tables only.", partition_fields=[f.get("name") for f in spec[0]["fields"]]) cur = current_fields(meta) why = v3_mismatch(cur, first) if why: raise Refused("schema_mismatch", "The files do not fit the table's schema: %s" % why, found=fields(first)) bad = crs_mismatch(cur) if bad: case = (" DuckDB 1.5 compares CRS names case-sensitively, and it types a plain GEOMETRY column it creates " "geometry(ogc:crs84): create the column as geometry(OGC:CRS84) (DuckDB: GEOMETRY('OGC:CRS84'); lhbox table " "create --column 'geom:geometry(OGC:CRS84)')." if bad[2].lower() == bad[3].lower() else "") raise Refused("geometry_crs_mismatch", "%s declares %s for column %s and the table's column is %s: registered, the table " "could not be read (no crs in GeoParquet metadata means OGC:CRS84).%s" % (bad[0], bad[2], bad[1], bad[3], case), file=bad[0], column=bad[1], file_crs=bad[2], table_crs=bad[3]) # 1. footers only, by range reads of the staged objects first, inspected, ranges, file_schemas = None, [], [], [] for obj in staged: p = obj["key"] try: with s3.open_input_file("%s/%s" % (fbucket, p)) as fh: pf = pq.ParquetFile(fh) schema, md = pf.schema_arrow, pf.metadata except Exception as exc: refuse("not_parquet", "%s is not a Parquet file pyarrow can read (%s)." % (p, first_line(exc)), file=p) if any((f.metadata or {}).get(b"PARQUET:field_id") is not None for f in schema): refuse("files_have_field_ids", "%s carries Iceberg field ids (written by an Iceberg engine): add_files registers files by " "column name and refuses them." % p, file=p) if first is None: first = schema elif not schema.remove_metadata().equals(first.remove_metadata()): refuse("schema_mismatch", "%s does not have the schema of %s." % (p, staged[0]["key"]), file=p, expected=fields(first), found=fields(schema)) rg = [(sum(md.row_group(i).column(j).total_compressed_size for j in range(md.num_columns)), md.row_group(i).num_rows) for i in range(md.num_row_groups)] # a row group is "large" over rg_warn_bytes, or over wide_rg_bytes when its rows are wide (over wide_row_bytes each on # average): few, large rows per row group mean a point read downloads many MB for one row flagged = [b for b, n in rg if b > req["rg_warn_bytes"] or (b > req["wide_rg_bytes"] and b > req["wide_row_bytes"] * max(n, 1))] info = {"file": p, "bytes": obj["size"], "rows": md.num_rows, "row_groups": md.num_row_groups, "largest_row_group_bytes": max(b for b, _ in rg) if rg else 0, "large_row_group_bytes": max(flagged) if flagged else 0} if sorted_by: if sorted_by not in first.names: refuse("sorted_by_not_a_column", "--sorted-by %s: the files have no such column (%s)." % (sorted_by, ", ".join(first.names)), column=sorted_by, columns=first.names) paths = [md.row_group(0).column(k).path_in_schema for k in range(md.num_columns)] if md.num_row_groups else [] j = paths.index(sorted_by) if sorted_by in paths else None st = [md.row_group(i).column(j).statistics for i in range(md.num_row_groups)] if j is not None else [] if st and all(s is not None and s.has_min_max for s in st): info["sorted_by_min"], info["sorted_by_max"] = min(s.min for s in st), max(s.max for s in st) ranges.append((info["sorted_by_min"], info["sorted_by_max"], p)) else: info["sorted_by_min"] = info["sorted_by_max"] = None inspected.append(info) file_schemas.append((p, schema, md)) warnings = [] big = [i for i in inspected if i["large_row_group_bytes"]] if big: largest = max(i["large_row_group_bytes"] for i in big) warnings.append({"code": "large_row_groups", "files": len(big), "largest_row_group_bytes": largest, "message": "%d file(s) have large row groups (largest %.1f MB; flagged over %.0f MB, or over %.0f MB of " "rows averaging more than %d KB): a query that needs one row downloads the whole row group of " "every column it reads; write smaller row groups if the table is read by point" % (len(big), largest / 1048576.0, req["rg_warn_bytes"] / 1048576.0, req["wide_rg_bytes"] / 1048576.0, req["wide_row_bytes"] >> 10)}) unsigned = [f.name for f in first if pa.types.is_unsigned_integer(f.type)] if unsigned: warnings.append({"code": "unsigned_columns", "columns": unsigned, "message": "unsigned column(s) %s: Iceberg has no unsigned integers, so the table declares them signed and " "the files keep their unsigned type; DuckDB reads them, other engines may refuse them or read " "values above the signed maximum as negative; write them signed to be safe" % ", ".join(unsigned)}) if sorted_by: nostats = [i["file"] for i in inspected if i.get("sorted_by_min") is None] if nostats: warnings.append({"code": "sorted_by_no_statistics", "files": len(nostats), "message": "%d file(s) have no min/max statistics for %s: readers cannot skip them by it" % (len(nostats), sorted_by)}) ranges.sort(key=lambda r: (r[0], r[1])) # a file overlaps when its minimum is within the widest range seen so far (a running maximum: one wide file can # cover many after it; review of #1660) over, widest = [], None for lo, hi, path in ranges: if widest is not None and lo <= widest[0]: over.append((widest[1], path)) if widest is None or hi > widest[0]: widest = (hi, path) if over: warnings.append({"code": "sorted_by_ranges_overlap", "overlaps": len(over), "example": list(over[0]), "message": "%d file(s) overlap another file's %s range (e.g. %s and %s): a filter on %s reads every " "file whose range covers the value; sort the rows across files to skip more" % (len(over), sorted_by, os.path.basename(over[0][0]), os.path.basename(over[0][1]), sorted_by)}) # 2. the table (a failure here, e.g. a schema PyIceberg cannot map, is before any copy: nothing to undo; review of #1660) v3 = bool(req.get("v3")) if v3: try: import lhbox_iceberg_core tpath, token, meta_loc, raw = rest_table() meta = json.loads(raw) except Exception as exc: answer({"error": "%s: %s" % (type(exc).__name__, first_line(exc)), "stage": "table", "files": 0, "deleted": 0, "left": [], "staged_kept": True}) sys.exit(1) try: v3_guard(meta) except Refused as r: refuse(r.code, r.message, **r.detail) loc = meta["location"].rstrip("/") else: try: from pyiceberg.catalog.rest import RestCatalog cat = RestCatalog(name="lhbox", uri=c["uri"], warehouse=c["warehouse"], credential=c["key_id"] + ":" + c["secret"], **{"s3.endpoint": c["s3_endpoint"], "s3.path-style-access": "true", "s3.region": "us-east-1", "s3.access-key-id": c["key_id"], "s3.secret-access-key": c["secret"]}) ident = (req["namespace"], req["name"]) if req["mode"] == "create": cat.create_namespace_if_not_exists(req["namespace"]) tx = cat.create_table_transaction(ident, schema=first, properties=req["properties"]) else: tbl = cat.load_table(ident) except Exception as exc: answer({"error": "%s: %s" % (type(exc).__name__, first_line(exc)), "stage": "table", "files": 0, "deleted": 0, "left": [], "staged_kept": True}) sys.exit(1) if req["mode"] != "create": fv = int(getattr(tbl.metadata, "format_version", 2)) if fv != 2: refuse("format_version_unsupported", "The table is format-version %d; add-files registers into format-version 2 tables " "only (PyIceberg 0.12 cannot load a v3 table with geometry)." % fv, format_version=fv) try: from pyiceberg.io.pyarrow import _check_pyarrow_schema_compatible except ImportError: _check_pyarrow_schema_compatible = None if _check_pyarrow_schema_compatible is not None: try: _check_pyarrow_schema_compatible(tbl.schema(), first) except Exception as exc: refuse("schema_mismatch", "The files do not fit the table's schema: %s" % str(exc).strip()[:1500], found=fields(first)) tx = tbl.transaction() loc = tx.table_metadata.location.rstrip("/") tbucket, tprefix = loc.split("://", 1)[1].split("/", 1) # 3. copy server-side, register, commit copied, inflight, stage, total, parts_total, geo = [], None, "copy", 0, 0, None geo_stats, kept_footers = {"files": 0, "column_chunks": 0}, [] try: for obj, (_, _, md) in zip(staged, file_schemas): key = "%s/data/%s.parquet" % (tprefix, uuid.uuid4()) source = "/%s/%s" % (fbucket, urllib.parse.quote(obj["key"], safe="/-_.~")) tail, written = None, obj["size"] if v3 and lacks_statistics(md): # DuckDB would never use its geospatial statistics: a new footer try: body_len, tail, chunks = new_tail(obj) except Exception as exc: kept_footers.append({"file": obj["key"], "error": first_line(exc)}) if tail is not None: inflight = (key, None) n_parts, written = copy_with_tail(tbucket, key, source, obj, body_len, tail) geo_stats["files"] += 1 geo_stats["column_chunks"] += chunks elif obj["size"] <= req["copy_max"]: inflight = (key, None) copy_call(tbucket, key, size=obj["size"], extra={"x-amz-copy-source": source}) n_parts = 1 else: text = s3_call("POST", tbucket, key, query="uploads") uid = re.search(r"([^<]+)", text).group(1) inflight = (key, uid) xml = [] for n, start in enumerate(range(0, obj["size"], req["part_bytes"]), 1): end = min(start + req["part_bytes"], obj["size"]) - 1 t = copy_call(tbucket, key, query="partNumber=%d&uploadId=%s" % (n, q(uid)), extra={"x-amz-copy-source": source, "x-amz-copy-source-range": "bytes=%d-%d" % (start, end)}) xml.append("%d%s" % (n, re.search(r"([^<]+)", t).group(1))) s3_call("POST", tbucket, key, query="uploadId=%s" % q(uid), data=("%s" % "".join(xml)).encode()) n_parts = len(xml) copied.append("s3://%s/%s" % (tbucket, key)) inflight = None total += written parts_total += n_parts stage = "register" if v3: io = {"s3.endpoint": endpoint, "s3.path-style-access": "true", "s3.region": "us-east-1", "s3.access-key-id": c["key_id"], "s3.secret-access-key": c["secret"]} tries = int(req.get("commit_tries") or 1) for attempt in range(tries): stage = "register" if attempt: time.sleep(min(2 ** attempt, 8)) # another writer (maintenance's commits are optimistic too) won # the table as it is now, checked again, with a token minted now: the copy may have taken longer than one tpath, token, meta_loc, raw = rest_table() meta = json.loads(raw) v3_guard(meta) body = json.loads(lhbox_iceberg_core.transaction.add_files( [req["namespace"], req["name"]], meta_loc, raw, copied, io, {"lhbox.add-files": "1"})) # geometry bounds, which add_files does not write (#2664: without them a `geom && box` filter reads every file) geo_ids = {f["name"]: f["id"] for f in current_fields(meta) if isinstance(f["type"], str) and GEO_TYPE.match(f["type"]) and f["type"].strip().lower().startswith("geometry")} bounds, geo_written = {}, [] for (p, schema, md), dest in zip(file_schemas, copied): boxes = {fid: geom_bounds(md, col) for col, fid in geo_ids.items()} boxes = {fid: b for fid, b in boxes.items() if b is not None} if boxes: bounds[dest] = boxes geo = {"columns": sorted(geo_ids), "files_with_bounds": 0, "files": len(copied)} if geo_ids else None if bounds: try: body, geo["files_with_bounds"], geo_written = with_geom_bounds(body, bounds) except Exception as exc: # pruning is lost, nothing else: commit what add_files built geo["error"] = "%s: %s" % (type(exc).__name__, first_line(exc)) if not (meta.get("properties") or {}).get("schema.name-mapping.default"): # the files carry no field ids: readers map their columns by name (what PyIceberg's add_files sets too) body["updates"].append({"action": "set-properties", "updates": { "schema.name-mapping.default": json.dumps(name_mapping(current_fields(meta)))}}) stage = "commit" try: rest("POST", tpath, token=token, body={"identifier": {"namespace": [req["namespace"]], "name": req["name"]}, "requirements": body["requirements"], "updates": body["updates"]}) break except (CommitConflict, CommitRejected) as exc: stage = "register" # the catalog said no: nothing is in, the copies are ours to delete drop_objects(geo_written) if isinstance(exc, CommitRejected) or attempt + 1 == tries: raise else: tx.add_files(copied) stage = "commit" tx.commit_transaction() except Exception as exc: out = {"error": "%s: %s" % (type(exc).__name__, first_line(exc)), "stage": stage, "files": len(copied), "staged_kept": True} if stage != "commit": if inflight is not None: # the copy in flight: abort its upload, or delete what it may have made try: s3_call("DELETE", tbucket, inflight[0], query=("uploadId=%s" % q(inflight[1])) if inflight[1] else "") except Exception: pass left = [] for d in copied: try: s3_call("DELETE", tbucket, d.split("://", 1)[1].split("/", 1)[1]) except Exception: left.append(d) out.update(deleted=len(copied) - len(left), left=left) if isinstance(exc, Refused): # the table changed under the copy (schema, partitioning, CRS) out = dict(out, refused=exc.code, message=exc.message, stage="register", **exc.detail) answer(out) sys.exit(1) if geo and geo["files_with_bounds"] < geo["files"]: warnings.append({"code": "no_geometry_bounds", "files": geo["files"] - geo["files_with_bounds"], "columns": geo["columns"], "error": geo.get("error"), "message": "%d of %d file(s) were registered without geometry bounds (%s): a spatial filter (&&, " "ST_Intersects) reads them whatever its box; write the files with Parquet's GEOMETRY type " "(DuckDB, GDAL 3.12) or a GeoParquet bbox covering column (geopandas write_covering_bbox=True, " "GDAL WRITE_COVERING_BBOX=YES), whose statistics give the bounds" % (geo["files"] - geo["files_with_bounds"], geo["files"], geo.get("error") or "no geospatial statistics nor bbox covering statistics in the file")}) if kept_footers: warnings.append({"code": "geometry_statistics_not_added", "files": len(kept_footers), "example": kept_footers[0], "message": "%d file(s) have geometry columns with geospatial statistics but no Parquet Statistics struct " "and were registered as they are (%s): DuckDB uses geospatial statistics only next to a " "Statistics struct, so a spatial filter (&&) skips no row group inside them; rewrite them " "with DuckDB (COPY ... (FORMAT parquet)), or add an empty Statistics to those column chunks" % (len(kept_footers), kept_footers[0]["error"])}) # 4. committed: the staged copies go, unless kept (a failure here is reported, never a failed command) deleted, staged_left = [], [] if not req["keep_staged"]: for obj in staged: try: s3_call("DELETE", fbucket, obj["key"]) deleted.append(obj["key"]) except Exception as exc: staged_left.append({"key": obj["key"], "error": first_line(exc)}) answer({"committed": True, "files": len(copied), "bytes": total, "copy_requests": parts_total, "warnings": warnings, "geometry_bounds": geo, "geometry_statistics_added": geo_stats if geo_stats["files"] else None, "inspected": inspected, "staged_deleted": deleted, "staged_left": staged_left, "peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * (1 if sys.platform == "darwin" else 1024)}) """.replace("@@ANSWER@@", _PY_ANSWER) def _positive_int(text): try: n = int(text) except ValueError: n = 0 if n < 1: raise argparse.ArgumentTypeError("a whole number of 1 or more, got %r" % text) return n class ImportNotCommitted(Exception): """A PyIceberg runner (--row-group-rows, add-files) failed before its commit (reading, writing, uploading or registering the files): nothing is in.""" class AddFilesRefused(Exception): """`table add-files` refused the files from their footers (a schema mismatch, field ids, not Parquet, a v3 table) before uploading anything; args[0] is the runner's answer: refused (the code), message, and the detail.""" def _py_answer(stdout): lines = [ln[len(_PY_ANSWER):] for ln in (stdout or "").splitlines() if ln.startswith(_PY_ANSWER)] try: return json.loads(lines[-1]) except (IndexError, ValueError): return None def _python_from_args(args): """The interpreter `--python PATH` / LHBOX_PYTHON name (resolved like duckdb_engine does), else the one running lhbox.""" wanted = getattr(args, "python", None) or _env("PYTHON") if not wanted: return sys.executable or "python3" exe = shutil.which(wanted) or (os.path.expanduser(wanted) if os.path.isfile(os.path.expanduser(wanted)) else None) if not exe: die_json("python_not_found", "No interpreter at %r (--python / LHBOX_PYTHON)." % wanted, EXIT_USAGE, remedy="Pass the path of a python that has pyiceberg installed, or unset LHBOX_PYTHON to use the one running lhbox.") return exe def pyiceberg_interpreter(args, engine=None, needs=("duckdb", "pyarrow"), why="--row-group-rows writes through PyIceberg (DuckDB cannot write small row groups)", core=False): """The python that runs a PyIceberg runner: for `table import --row-group-rows`, the one whose duckdb runs the import (--python / LHBOX_PYTHON, else the one running lhbox; with the duckdb binary, the python running lhbox); with no engine (`table add-files`), --python / LHBOX_PYTHON or the one running lhbox. Exit 1 when it lacks any of `needs` or pyiceberg 0.12+ (and, with core, lakehousebox-iceberg-core ICEBERG_CORE_MIN+), naming what to install there.""" exe = getattr(engine, "interpreter", None) or (sys.executable or "python3" if engine is not None else _python_from_args(args)) try: r = subprocess.run([exe, "-c", _PYICEBERG_PROBE], capture_output=True, text=True, timeout=120) found = _py_answer(r.stdout) or {} except (OSError, subprocess.TimeoutExpired): found = {} pyi = _parse_version(found.get("pyiceberg") or "") core_v = _parse_version(found.get("lhbox_iceberg_core") or "") missing = [m for m in needs if not found.get(m)] core_missing = core and (not core_v or core_v[:2] < ICEBERG_CORE_MIN) if missing or not pyi or pyi[:2] < PYICEBERG_MIN or core_missing: what = ", ".join(missing + ([] if pyi and pyi[:2] >= PYICEBERG_MIN else ["pyiceberg %s (found %s)" % (_dotted(PYICEBERG_MIN), found.get("pyiceberg") or "none")]) + (["%s %s (found %s)" % (ICEBERG_CORE_DIST, _dotted(ICEBERG_CORE_MIN), found.get("lhbox_iceberg_core") or "none")] if core_missing else [])) pkgs = " ".join(["'pyiceberg[pyarrow]>=%s'" % _dotted(PYICEBERG_MIN)] + (["'duckdb>=%s'" % _dotted(DUCKDB_MIN)] if "duckdb" in needs else []) + (["'%s>=%s' --find-links %s" % (ICEBERG_CORE_DIST, _dotted(ICEBERG_CORE_MIN), ICEBERG_CORE_FIND_LINKS)] if core else [])) die_json("iceberg_core_not_found" if core_missing and not missing and pyi and pyi[:2] >= PYICEBERG_MIN else "pyiceberg_not_found", "%s, and %s lacks %s." % (why, exe, what), EXIT_ERROR, interpreter=exe, found=found, remedy="%s -m pip install %s, or point --python / LHBOX_PYTHON at an interpreter that has them." % (exe, pkgs)) return exe, found def _run_pyiceberg_runner(exe, runner, req): """Run a PyIceberg runner script in `exe`, the request (with the catalog's key pair) on stdin, never in argv -> its answer. Raises AddFilesRefused when it refused before uploading anything, ImportNotCommitted when it failed before its commit (saying whether the files it uploaded were deleted), DuckDBFailure when the commit itself failed or the runner died without an answer (the caller asks the table whether the commit landed: import_insert_failed).""" try: r = subprocess.run([exe, "-c", runner], input=json.dumps(req), capture_output=True, text=True) except OSError as e: raise DuckDBFailure("cannot run %s: %s" % (exe, e)) ans = _py_answer(r.stdout) or {} if r.returncode == 0 and ans.get("committed"): return ans if ans.get("refused"): raise AddFilesRefused(ans) if ans.get("error"): if ans.get("stage") == "commit": note = "the commit itself failed (%d data file(s) kept: the table decides whether they are in)" % ans.get("files", 0) elif ans.get("left"): note = ("before the commit; %d uploaded data file(s) deleted, %d left behind (orphans, removed by maintenance): %s" % (ans.get("deleted", 0), len(ans["left"]), ", ".join(ans["left"][:5]))) else: note = "before the commit; the %d data file(s) this run uploaded were deleted" % ans.get("deleted", 0) cls = DuckDBFailure if ans.get("stage") == "commit" else ImportNotCommitted raise cls("%s (%s)" % (ans["error"], note)) lines = (r.stderr or r.stdout or "python exited %d" % r.returncode).strip().splitlines() raise DuckDBFailure(lines[-1] if lines else "python exited %d" % r.returncode) def pyiceberg_append(exe, rec, args, projection, order_column, parquet_files, properties): """Run _PYICEBERG_RUNNER in `exe`: the request (with the catalog's key pair) goes on stdin, never in argv -> the runner's answer (files, rows, peak_rss_bytes). Raises DuckDBFailure on any failure, saying whether the files this run uploaded were deleted; the caller asks the table whether the commit landed (import_insert_failed).""" f = recipe_fields(rec) req = {"catalog": {"uri": f["uri"], "warehouse": "s3://%s/" % f["bucket"], "s3_endpoint": rec["storage_endpoint"], "key_id": f["client_id"], "secret": f["client_secret"]}, "namespace": args.namespace, "name": args.name, "mode": args.mode, "projection": projection, "order_column": order_column, "parquet_files": parquet_files, "properties": properties, "batch_rows": PYICEBERG_BATCH_ROWS, "row_group_rows": args.row_group_rows, "target_bytes": ROW_GROUP_FILE_BYTES, "memory_limit": ROW_GROUP_MEMORY_LIMIT, "range_bytes": ROW_GROUP_RANGE_BYTES} return _run_pyiceberg_runner(exe, _PYICEBERG_RUNNER, req) def add_files_run(exe, rec, args, staged, sorted_by, v3=False): """Run _ADD_FILES_RUNNER in `exe` over the staged objects ([{key, size}] in the catalog's files bucket) -> its answer (files, bytes, copy_requests, warnings, inspected, staged_deleted, staged_left, peak_rss_bytes); raises as _run_pyiceberg_runner says. A created table is always format-version 2; with v3 (an existing format-version 3 table) the runner commits through the REST catalog with lakehousebox-iceberg-core instead of PyIceberg. The runner signs its copy requests with _sigv4_headers' own source (one implementation).""" import inspect import textwrap f = recipe_fields(rec) req = {"catalog": {"uri": f["uri"], "warehouse": "s3://%s/" % f["bucket"], "s3_endpoint": rec["storage_endpoint"], "key_id": f["client_id"], "secret": f["client_secret"]}, "files_bucket": rec["blob_bucket"], "staged": staged, "keep_staged": bool(getattr(args, "keep_staged", False)), "namespace": args.namespace, "name": args.name, "mode": args.mode, "sorted_by": sorted_by, "properties": {"format-version": "2"}, "rg_warn_bytes": ADD_FILES_ROW_GROUP_WARN_BYTES, "wide_rg_bytes": ADD_FILES_WIDE_ROW_GROUP_BYTES, "wide_row_bytes": ADD_FILES_WIDE_ROW_BYTES, "copy_max": ADD_FILES_COPY_MAX_BYTES, "part_bytes": ADD_FILES_COPY_PART_BYTES, "timeout": ADD_FILES_HTTP_TIMEOUT, "v3": v3, "commit_tries": ADD_FILES_V3_COMMIT_TRIES} runner = _ADD_FILES_RUNNER.replace("@@SIGV4@@", textwrap.dedent(inspect.getsource(_sigv4_headers))) return _run_pyiceberg_runner(exe, runner, req) _ADD_FILES_REMEDIES = { "schema_mismatch": "Write every file with the same columns and types (and, with --mode append, the table's), then run it again.", "files_have_field_ids": "These files came from an Iceberg engine: add them with that engine, or rewrite them without the " "PARQUET:field_id metadata (pyarrow: pq.write_table(table.cast(pa.schema([f.remove_metadata() for " "f in table.schema])), path)).", "not_parquet": "Stage Parquet files only (lhbox table import reads CSV).", "sorted_by_not_a_column": "Name a column the files have, or leave out --sorted-by.", "format_version_unsupported": "Add the files to a format-version 2 or 3 table (--mode create makes a format-version 2 one; " "lhbox table create --format-version 3 makes a v3 one to append to), or use lhbox table " "import, which rewrites the rows.", "partitioned_table": "Add the files to an unpartitioned table, or use lhbox table import, which writes partitioned tables.", "geometry_crs_mismatch": "Add the files to a table whose geometry column has the files' CRS, spelled the same (case " "included: geometry(OGC:CRS84) for lon/lat), or write the files' CRS as the table's: the crs of " "Parquet's GEOMETRY type when the column has that type, else the GeoParquet crs (PROJJSON with " "its id, e.g. {\"id\": {\"authority\": \"EPSG\", \"code\": 4326}}).", } _GLOB_CHARS = re.compile(r"[*?\[]") def _key_glob(pattern): """A compiled pattern for a key glob: * and ? stay within one folder, ** crosses folders (**/ also matches no folder: staging/**/*.parquet takes staging/a.parquet, as in git and the shells' globstar), [...] is a class, [!...] (or [^...]) its negation.""" out, i = "", 0 while i < len(pattern): ch = pattern[i] if pattern.startswith("**/", i) and (i == 0 or pattern[i - 1] == "/"): # a whole segment only: x**/ is x*/ out, i = out + "(?:.*/)?", i + 3 continue if pattern.startswith("**", i): out, i = out + ".*", i + 2 continue if ch == "*": out += "[^/]*" elif ch == "?": out += "[^/]" elif ch == "[": j = pattern.find("]", i + 1) if j < 0: out += re.escape(ch) else: body = pattern[i + 1:j] neg = body[:1] in ("!", "^") body = (body[1:] if neg else body).replace("\\", "\\\\").replace("^", "\\^") out, i = out + ("[^/" if neg else "[") + body + "]", j + 1 continue else: out += re.escape(ch) i += 1 return re.compile(out) def _staged_files(args, specs): """The catalog files `table add-files` names -> ([{key, size}] in order, once each; the specs that matched nothing; the keys a folder held that are not .parquet). A spec is a key (staging/a.parquet), a folder (staging/iberia/: every .parquet under it) or a glob (staging/iberia/*.parquet; ** crosses folders), listed through the API like file ls.""" out, seen, missing, skipped, reserved = [], set(), [], [], set() named = [s for s in specs if _file_reserved(s)] if named: # the platform's own files: a scheduled SQL sink's pending runs are Parquet under _sink//, and add-files # would copy them into this table, then delete them before the sink's roll could commit them to its own die_json("reserved_key", "%s: %s, and add-files does not take them." % (", ".join(named), FILE_RESERVED_WHAT), EXIT_USAGE, sources=named, remedy="Stage the files under a folder of your own (lhbox file put staging//) and name that.") for spec in specs: m = _GLOB_CHARS.search(spec) if m: prefix = spec[:m.start()] prefix = prefix[:prefix.rfind("/") + 1] rx = _key_glob(spec) objects, _, _ = _file_listing(args, prefix) hits = [o for o in objects if rx.fullmatch(o["key"])] elif spec.endswith("/") or not spec: objects, _, _ = _file_listing(args, spec) # a folder from the root ('') holds the platform's files too, Parquet or not: those are reported as its own reserved.update(o["key"] for o in objects if _file_reserved(o["key"])) objects = [o for o in objects if not _file_reserved(o["key"])] hits = [o for o in objects if o["key"].lower().endswith(".parquet")] skipped += [o["key"] for o in objects if not o["key"].lower().endswith(".parquet")] else: objects, _, _ = _file_listing(args, spec) hits = [o for o in objects if o["key"] == spec] # a glob from the root ('**/*.parquet') lists the platform's area too: never a staged file mine = [o["key"] for o in hits if _file_reserved(o["key"])] reserved.update(mine) hits = [o for o in hits if not _file_reserved(o["key"])] if not hits and not mine: # it matched, only the platform's: said once, below missing.append(spec) for o in sorted(hits, key=lambda o: o["key"]): if o["key"] not in seen: seen.add(o["key"]) out.append({"key": o["key"], "size": int(o.get("size") or 0)}) return out, missing, skipped, sorted(reserved) def cmd_table_add_files(args): ref = getattr(args, "table_ref", None) if ref and (os.path.exists(ref) or "/" in ref or re.search(r"\.parquet$", ref, re.I)): die("Name the table first: lhbox table add-files [catalog.]namespace.table KEY… (%r looks like a file)." % ref, EXIT_USAGE) args.namespace, args.name = _table_ref(args) remote = [s for s in args.sources if s.startswith(REMOTE_SCHEMES)] # only an explicit local spelling is refused here: a bare relative name is a key, even when a folder of that name # exists here too (the docs' own example stages out/ as staging/spain/; review of #1660) local = [s for s in args.sources if s.startswith(("/", "~", "./", "../", ".\\"))] if remote or local: what = (remote or local)[0] die_json("not_a_catalog_file", "add-files takes files already in the catalog's files (keys such as staging/x.parquet); " "%s is %s." % (what, "a URL" if remote else "a file on this machine"), EXIT_USAGE, sources=remote + local, remedy="Stage them first, then add them: lhbox file put %s staging//%s, then lhbox table add-files " "%s.%s staging// (or lhbox table import, which reads local files and URLs and rewrites the rows)." % (local[0] if local else "", " --catalog " + catalog_arg(args) if catalog_arg(args) else "", args.namespace, args.name)) wid = resolve_catalog(args) staged, missing, skipped, reserved = _staged_files(args, args.sources) if not staged and reserved: die_json("no_staged_files", "Only the platform's own files matched %s (e.g. %s): %s, and add-files does not take " "them." % (", ".join(args.sources), reserved[0], FILE_RESERVED_WHAT), EXIT_NOTFOUND, sources=args.sources, platform_files_left_out=reserved, remedy="Stage your files under a folder of your own (lhbox file put staging//) and name that.") if not staged: here = [s for s in args.sources if os.path.exists(os.path.expanduser(s))] die_json("no_staged_files", "Nothing in the catalog's files matched: %s" % ", ".join(args.sources), EXIT_NOTFOUND, sources=args.sources, remedy=("%s is on this machine, not in the catalog's files: stage it first with lhbox file put %s , then " "name that key. " % (here[0], here[0]) if here else "") + "lhbox file ls / lists what is staged; stage files with lhbox file put.") if missing: print("note: nothing matched %s" % ", ".join(missing), file=sys.stderr) if skipped: print("note: %d file(s) in the folder(s) are not .parquet and were left out (e.g. %s)" % (len(skipped), skipped[0]), file=sys.stderr) if reserved: print("note: %d of the platform's own file(s) matched and were left out (e.g. %s): %s" % ( len(reserved), reserved[0], FILE_RESERVED_WHAT), file=sys.stderr) rec = _require_static_recipe(request(args, "GET", "/v1/connection?" + urllib.parse.urlencode( {"catalog_id": wid, "engine": "duckdb"}), timeout=90), "table add-files") if rec.get("level") != "write": die_json("read_only_level", "This credential holds %s on the catalog; adding files needs write." % (rec.get("level") or "no grant"), EXIT_AUTH, level=rec.get("level"), identity=rec.get("identity"), remedy="Ask an admin for a write grant (lhbox catalog grant --level write), or connect with a write-level key.") if not rec.get("blob_bucket"): die_json("no_files_bucket", "The connection recipe names no files bucket for this catalog.", EXIT_SERVER, remedy="Update the CLI (lhbox update); if it repeats, report it.") q = urllib.parse.urlencode({"catalog": wid, "namespace": args.namespace, "name": args.name}) st, existing = request_status(args, "GET", "/v1/table?" + q + "&snapshots=%d" % SNAPSHOT_LOOKBACK) if st not in (200, 404): _fail("GET", "/v1/table", st, existing) if args.mode == "create" and st == 200: die_json("table_exists", "%s.%s already exists in catalog %s (%s rows, %s snapshots)." % (args.namespace, args.name, rec.get("warehouse_name"), "?" if existing.get("rows") is None else existing.get("rows"), existing.get("snapshots")), EXIT_LIMIT, table=existing.get("table"), rows=existing.get("rows"), snapshots=existing.get("snapshots"), remedy="--mode append adds these files to it as one commit; or name another table.") if args.mode == "append" and st == 404: _fail("GET", "/v1/table", st, existing) fv = int(existing.get("format_version") or 2) if args.mode == "append" else 2 if fv not in (2, 3): die_json("format_version_unsupported", "%s.%s is format-version %s; add-files registers into format-version 2 and 3 " "tables." % (args.namespace, args.name, fv), EXIT_USAGE, format_version=fv, remedy=_ADD_FILES_REMEDIES["format_version_unsupported"]) before = existing if st == 200 else {"rows": 0, "snapshots": 0} exe, found = pyiceberg_interpreter(args, None, needs=("pyarrow",), core=fv == 3, why="add-files into a format-version 3 table checks the files with PyIceberg and " "builds the commit with %s (PyIceberg 0.12 cannot write one)" % ICEBERG_CORE_DIST if fv == 3 else "add-files registers the files through PyIceberg (add_files)") t0 = time.time() print("adding %d staged file(s) (%s) to %s.%s: copied in the store, ONE commit…" % (len(staged), fmt_bytes(sum(o["size"] for o in staged)), args.namespace, args.name), file=sys.stderr) try: ans = add_files_run(exe, rec, args, staged, getattr(args, "sorted_by", None), v3=fv == 3) except AddFilesRefused as exc: detail = dict(exc.args[0]) code = detail.pop("refused") message = detail.pop("message", code) detail.pop("stage", None) done = ("Nothing was committed; the %d copies were deleted%s and the staged files are untouched. " % ( detail.get("files"), (", %d left as orphans (maintenance removes them)" % len(detail["left"])) if detail.get("left") else "") if detail.get("files") else "Nothing was copied or committed; the staged files are untouched. ") die_json(code, message, EXIT_USAGE if code == "format_version_unsupported" else EXIT_ERROR, committed=False, outcome="failed", remedy=done + _ADD_FILES_REMEDIES.get(code, "Fix the files and run it again."), **detail) except ImportNotCommitted as exc: die_json("add_files_failed", str(exc), EXIT_ERROR, committed=False, outcome="failed", staged_kept=True, remedy="Nothing was committed%s and the staged files are kept; fix the cause and run the same command again." % ("" if args.mode == "append" else " and the table was not created")) except DuckDBFailure as exc: # the commit itself, or no answer: ask the table import_insert_failed(args, q, before, exc) # returns only when the append landed # the runner never reached its clean-up: every staged file is still there (review of #1660) ans = {"staged_left": [] if getattr(args, "keep_staged", False) else [{"key": o["key"], "error": "not deleted: the run ended without an answer after its commit"} for o in staged]} seconds = round(time.time() - t0, 2) after = request(args, "GET", "/v1/table?" + q) inspected = ans.get("inspected") or [] out = {"table": after.get("table"), "warehouse": after.get("warehouse"), "warehouse_id": _cid(after), "mode": args.mode, "files": len(staged), "bytes": ans.get("bytes"), "seconds": seconds, "rows": _rows_appended(before, after), "rows_total": after.get("rows"), "commits": (after.get("snapshots") or 0) - (before.get("snapshots") or 0), "snapshots": after.get("snapshots"), "format_version": after.get("format_version"), "data_files": ans.get("files"), "copy_requests": ans.get("copy_requests"), "writer": ("%s %s add_files, copied in the store" % (ICEBERG_CORE_DIST, found.get("lhbox_iceberg_core")) if fv == 3 else "pyiceberg %s add_files, copied in the store" % found.get("pyiceberg")), "sorted_by": getattr(args, "sorted_by", None), "warnings": ans.get("warnings") or [], "geometry_bounds": ans.get("geometry_bounds"), "geometry_statistics_added": ans.get("geometry_statistics_added"), "keep_staged": bool(getattr(args, "keep_staged", False)), "staged_deleted": len(ans.get("staged_deleted") or []), "staged_left": ans.get("staged_left") or [], "row_groups": sum(i.get("row_groups") or 0 for i in inspected) if inspected else None, "largest_row_group_bytes": max((i.get("largest_row_group_bytes") or 0 for i in inspected), default=None), "peak_rss_bytes": ans.get("peak_rss_bytes")} if reserved: out["platform_files_left_out"] = reserved if getattr(args, "full", False): out["inspected"] = inspected # every staged file's key, rows, row groups and --sorted-by range: on request if out["staged_left"]: print("warning: the files are in the table, but %d staged file(s) could not be deleted (e.g. %s): remove them with " "lhbox file rm" % (len(out["staged_left"]), out["staged_left"][0].get("key")), file=sys.stderr) if _want_json(args): print_json(out) return print("%s: %s from %d staged Parquet file(s)%s copied in the store and added in %s s, %d commit(s) (%s snapshot(s) " "now), format-version %s; staged files %s" % (out["table"], "rows" if out["rows"] is None else "%s rows" % out["rows"], out["files"], (" (%s)" % fmt_bytes(out["bytes"])) if out["bytes"] is not None else "", seconds, out["commits"], out["snapshots"], out["format_version"], "kept" if out["keep_staged"] else "deleted (%d)" % out["staged_deleted"])) if out["rows"] is None: print(ROWS_NOT_AVAILABLE) if out["geometry_statistics_added"]: print("%d file(s) got an empty Parquet Statistics on their geometry column chunks (a new footer, the data pages as " "they were): DuckDB uses geospatial statistics only next to one" % out["geometry_statistics_added"]["files"]) for w in out["warnings"]: print("warning: " + (w.get("message") or w.get("code") or "")) def cmd_table_import(args): _import_table_ref(args) files, missing = expand_sources(args.sources) if not files: die_json("no_input_files", "No file matched: %s" % ", ".join(args.sources), EXIT_USAGE, sources=args.sources, remedy="Name Parquet or CSV files or globs (data/*.parquet, 'data/**/*.csv' quoted), or URLs DuckDB can read (s3://, https://).") if missing: print("note: nothing matched %s" % ", ".join(missing), file=sys.stderr) if args.mode == "append" and args.format_version is not None: die_json("format_version_on_append", "--format-version applies when the table is created; --mode append writes into the table as it is.", EXIT_USAGE) fmt = detect_format(files, getattr(args, "format", None)) source = source_expr(files, fmt) wid = resolve_catalog(args) engine = duckdb_engine(args) rec = _require_static_recipe(request(args, "GET", "/v1/connection?" + urllib.parse.urlencode( {"catalog_id": wid, "engine": "duckdb"}), timeout=90), "table import") if rec.get("level") != "write": die_json("read_only_level", "This credential holds %s on the catalog; importing needs write." % (rec.get("level") or "no grant"), EXIT_AUTH, level=rec.get("level"), identity=rec.get("identity"), remedy="Ask an admin for a write grant (lhbox catalog grant --level write), or connect with a write-level key.") alias = recipe_fields(rec)["alias"] # checked (L6); recipe_session below builds the ATTACH from the same target = "%s.%s.%s" % (sql_ident(alias), sql_ident(args.namespace), sql_ident(args.name)) q = urllib.parse.urlencode({"catalog": wid, "namespace": args.namespace, "name": args.name}) # with its snapshot log: what import_insert_failed compares against should the commit's answer be lost st, existing = request_status(args, "GET", "/v1/table?" + q + "&snapshots=%d" % SNAPSHOT_LOOKBACK) if st not in (200, 404): _fail("GET", "/v1/table", st, existing) if args.mode == "create" and st == 200: die_json("table_exists", "%s.%s already exists in catalog %s (%s rows, %s snapshots)." % (args.namespace, args.name, rec.get("warehouse_name"), "?" if existing.get("rows") is None else existing.get("rows"), existing.get("snapshots")), EXIT_LIMIT, table=existing.get("table"), rows=existing.get("rows"), snapshots=existing.get("snapshots"), remedy="--mode append adds these files to it as one commit; or choose another --name.") if args.mode == "append" and st == 404: _fail("GET", "/v1/table", st, existing) before = existing if st == 200 else {"rows": 0, "snapshots": 0} # the files, inspected locally: schema, and the GeoParquet metadata if any (a CSV carries none) try: describe = engine.run("DESCRIBE SELECT * FROM " + source) geo_by_file = _read_geo_metadata(engine, files) if fmt == "parquet" else {} except Exception as exc: # noqa: BLE001 - DuckDB's own error classes _duckdb_die(exc) if not describe: die_json("no_columns", "DuckDB found no columns in the files.", EXIT_ERROR, files=files[:10]) geometry_cols = [r["column_name"] for r in describe if _is_geometry_type(r["column_type"])] geo_props = geoparquet_properties(geo_by_file) # a geometry import gets the spatial layout (SPATIAL_ROW_GROUP_PROPERTY's comment: mostly temporary DuckDB workarounds) spatial = bool(geometry_cols) and fmt == "parquet" primary_geom = primary_geometry_column(geometry_cols, geo_props) if spatial else None file_columns = [r["column_name"] for r in describe] # which format version the table will have, and therefore which path creates it fv_source = None if args.mode == "create": if args.format_version is not None: fv, fv_source = args.format_version, "request" else: cat = request(args, "GET", "/v1/catalogs/%s" % urllib.parse.quote(wid)) fv, fv_source = int(cat.get("default_format_version") or 3), "catalog_default" else: fv, fv_source = int(existing.get("format_version") or 2), "existing_table" rgr = getattr(args, "row_group_rows", None) if rgr and (fv == 3 or geometry_cols): die_json("row_group_rows_unsupported", "--row-group-rows writes through PyIceberg, format-version 2 tables without geometry columns only; this %s." % ("table is format-version 3" if fv == 3 else "file has geometry column(s) %s" % ", ".join(geometry_cols)), EXIT_USAGE, format_version=fv, geometry_columns=geometry_cols, remedy="--format-version 2 for a new table, or import without --row-group-rows (DuckDB's own row groups).") if rgr: path = "pyiceberg_create_and_append" if args.mode == "create" else "pyiceberg_append" pyi_exe, pyi_found = pyiceberg_interpreter(args, engine) elif args.mode == "create" and fv == 3: path = "api_create_then_insert" elif args.mode == "create": path = "duckdb_create_then_insert" else: path = "duckdb_insert" # the projection: geometry columns go to a v3 table typed, to a v2 table as WKB (what geo.encoding says) session = recipe_session(rec, engine.version) need_spatial = bool(geometry_cols) and fv == 2 if need_spatial: session = ["INSTALL spatial; LOAD spatial;"] + session columns = [r["column_name"] for r in describe] # an append into a table that has all four bbox columns (added by hand, or by CLI 0.4.1's --bbox-columns) while the # files lack them fills them from the geometry: rows with NULL bounds would be missed by a filter on those columns bbox_active = False if args.mode == "append": table_cols = [c["name"] for c in existing.get("schema", [])] extra = [c for c in columns if c not in table_cols] if extra: die_json("columns_not_in_table", "The files have columns the table lacks: %s." % ", ".join(extra), EXIT_ERROR, columns=extra, table_columns=table_cols, remedy="Drop or rename them in the files, or add the columns to the table first (ALTER TABLE in DuckDB).") bbox_active = spatial and all(c in table_cols for c in BBOX_COLUMNS) and not any(c in file_columns for c in BBOX_COLUMNS) order = table_cols else: order = columns # the target's column types, for the geometry re-typing below: the schema this import creates, or the table's own schema, target_types = None, {} if path == "api_create_then_insert": try: schema = schema_from_describe(describe, fv) except GeometryCRSUnsupported as e: col, typ = e.args # refused BEFORE the create: the catalog would accept geometry(projjson:...) and leave a table DuckDB cannot write die_json("geometry_crs_without_authority", "Column %r is a geometry whose CRS names no authority code (%s). A format-version 3 table needs an " "AUTHORITY:CODE CRS that DuckDB can write; Iceberg's projjson: form is not writable by DuckDB 1.5.5." % (col, typ), EXIT_ERROR, column=col, type=typ[:300], remedy="--format-version 2 imports it as WKB and keeps the full PROJJSON in geo.crs.projjson; or re-tag " "the files' CRS with its code (in DuckDB: COPY (SELECT * REPLACE (ST_SetCRS(%s, 'EPSG:') AS %s) " "FROM read_parquet('')) TO '') and import that." % (sql_ident(col), sql_ident(col))) except ValueError as e: col, typ = e.args die_json("unmapped_type", "Column %r has DuckDB type %s, which has no Iceberg equivalent." % (col, typ), EXIT_ERROR, column=col, type=typ, remedy="Cast it in a view or a copy of the file first (e.g. to VARCHAR), then import that.") target_types = {f["name"]: f["type"] for f in schema["fields"]} elif args.mode == "append": target_types = {c.get("name"): c.get("type") for c in existing.get("schema", [])} source_types = {r["column_name"]: r["column_type"] for r in describe} # DuckDB's core knows almost no CRS: without the spatial extension a GEOMETRY('EPSG:25830') column cannot even be # declared ("Encountered unrecognized coordinate system 'EPSG:25830'", DuckDB 1.5.5, measured 2026-09-28), so a v3 # import of any geometry with a CRS other than the default loads it if fv >= 3 and not need_spatial and any(not _same_crs(_geo_crs_of_duckdb_type(source_types.get(c), ("GEOMETRY", "GEOGRAPHY")) or "", "") or not _same_crs(_geo_crs_of_iceberg_type(target_types.get(c)), "") for c in geometry_cols): need_spatial = True session = ["INSTALL spatial; LOAD spatial;"] + session # the spatial order and the bbox columns call ST_Hilbert / ST_XMin…, which live in the spatial extension hilbert = (spatial and not getattr(args, "order_by", None) and not getattr(args, "no_order", False) and source_types[primary_geom].strip().upper().startswith("GEOMETRY")) if (hilbert or bbox_active) and not need_spatial: need_spatial = True session = ["INSTALL spatial; LOAD spatial;"] + session # a geometry import reads its files under an alias, so the ORDER BY and the bbox expressions name the FILES' geometry # column, never the projected output column of the same name (WKB in a v2 table) src_geom = "%s.%s" % (SOURCE_ALIAS, sql_ident(primary_geom)) if spatial else None exprs, casts = [], [] for c in order: if bbox_active and c in BBOX_COLUMNS: exprs.append("%s(%s) AS %s" % (BBOX_FUNCTIONS[BBOX_COLUMNS.index(c)], src_geom, sql_ident(c))) elif c not in columns: exprs.append("NULL AS %s" % sql_ident(c)) elif c in geometry_cols and fv == 2: exprs.append("ST_AsWKB(%s) AS %s" % (sql_ident(c), sql_ident(c))) elif c in geometry_cols: exprs.append(geometry_select_expr(c, source_types[c], target_types.get(c))) elif unsigned_cast(source_types.get(c)): exprs.append("CAST(%s AS %s) AS %s" % (sql_ident(c), unsigned_cast(source_types[c]), sql_ident(c))) casts.append({"column": c, "from": source_types[c].strip(), "to": unsigned_cast(source_types[c])}) else: exprs.append(sql_ident(c)) for cast in casts if not _json_mode() else []: # JSON: the report's `casts`; stderr is one envelope or nothing print("warning: column %s is %s, which Iceberg lacks: written as %s" % (cast["column"], cast["from"], cast["to"]), file=sys.stderr) # the order (platform/docs/performance.md): --order-by names a column, --no-order none; else a geometry import is # written in Hilbert order of its primary geometry (research/49a §5: rows clustered in space, so files and row groups # have tight bounds) and any other import by its first DATE/TIMESTAMP column. A geometry import runs single-threaded # (SPATIAL_SESSION_SQL: the only way DuckDB 1.5 keeps an order across Iceberg files); any other keeps insertion order. order_col, order_source, order_expr = None, None, None if getattr(args, "order_by", None): if args.order_by not in columns: die_json("column_not_found", "--order-by %s names a column the files do not have." % args.order_by, EXIT_USAGE, column=args.order_by, columns=columns, remedy="Name one of 'columns', or --no-order to keep the files' own order.") order_col, order_source = args.order_by, "request" order_expr = ("%s.%s" % (SOURCE_ALIAS, sql_ident(order_col))) if spatial else sql_ident(order_col) elif hilbert: order_col, order_source = "hilbert(%s)" % primary_geom, "default_spatial" order_expr = "ST_Hilbert(%s, %s)" % (src_geom, hilbert_extent_expr(primary_geom, source, geo_props)) elif not getattr(args, "no_order", False) and not spatial: order_col = default_order_column(describe) order_source = "default" if order_col else None order_expr = sql_ident(order_col) if order_col else None select = ("SELECT %s FROM %s" % (", ".join(exprs), ("%s AS %s" % (source, SOURCE_ALIAS)) if spatial else source) + (" ORDER BY %s" % order_expr if order_expr else "")) if spatial: session.extend(SPATIAL_SESSION_SQL) elif order_col: session.append(PRESERVE_ORDER_SQL) if engine.version and engine.version < (2, 0, 0): # DuckDB 1.5 refuses every INSERT into a PARTITIONED table that carries write.target-file-size-bytes ("currently # not supported for partitioned tables"), and this import puts that property on every table it writes: an append # into a time-partitioned table failed before writing anything (#3008; the sink roller sets the same, worker/roll.py) session.insert(0, IGNORE_PARTITIONED_FILE_SIZE_SQL) statement = "INSERT INTO %s %s;" % (target, select) # the ONE data commit, whatever the path if rgr: statement = select # what the PyIceberg runner reads, then appends in one commit setup_statements = [] # what DuckDB runs before it: the create, the layout property created_via_api, layout_via = None, None # TEMPORARY (SPATIAL_ROW_GROUP_PROPERTY): a geometry import's own INSERT writes ~8 MB row groups; the property goes on # the table before the INSERT and is removed right after it (drop_row_group_property), because left there it makes # every plain DuckDB INSERT into the table fail. A table that already carries it keeps its owner's value. rg_set, rg_state, rg_applied = False, None, False rg_props = {SPATIAL_ROW_GROUP_PROPERTY: SPATIAL_ROW_GROUP_BYTES} if spatial and args.mode == "append" and SPATIAL_ROW_GROUP_PROPERTY in (existing.get("properties") or {}): rg_state = "kept_owner_value" elif spatial: rg_set = True pyi_props, pyi_answer = {}, {} if rgr: # the row-group limit stays on the table (DuckDB ignores it; it says how the files were written); the layout # properties as on the other paths: set at the create, on an append only where the table lacks them have = (existing.get("properties") or {}) if args.mode == "append" else {} pyi_props = {k: v for k, v in LAYOUT_PROPERTIES.items() if k not in have} if have.get(ROW_GROUP_LIMIT_PROPERTY) != str(rgr): pyi_props[ROW_GROUP_LIMIT_PROPERTY] = str(rgr) layout_via = "pyiceberg" elif path == "api_create_then_insert": body = {"catalog_id": wid, "namespace": args.namespace, "name": args.name, "schema": schema, "format_version": fv, "properties": dict(LAYOUT_PROPERTIES, **(rg_props if rg_set else {}))} created_via_api = request(args, "POST", "/v1/tables", body, args.idempotency_key) for w in created_via_api.get("warnings", []): print("warning: " + w, file=sys.stderr) layout_via = "api" elif path == "duckdb_create_then_insert": # the API path creates the namespace on demand; DuckDB's create wants the schema there first (measured live # 2026-09-21: 'Schema with name "imp" does not exist'). A namespace is not a table commit. The table is created # EMPTY with DuckDB's own column types, given its target file size, then filled: a CTAS would have written its # files at the writer's ~7 MB default before any property could apply (measured 2026-09-23, research/30 §5d) session.append("CREATE SCHEMA IF NOT EXISTS %s.%s;" % (sql_ident(alias), sql_ident(args.namespace))) setup_statements = ["CREATE TABLE %s (%s);" % (target, ", ".join(duckdb_column_def(r, fv) for r in describe)), layout_properties_call(alias, args.namespace, args.name, dict(LAYOUT_PROPERTIES, **(rg_props if rg_set else {})))] layout_via = "duckdb" else: # an append sets the target file size only on a table that lacks it: the owner's own value stands have = existing.get("properties") or {} # only on a table without a file size (as before the codec), and never over a key the owner set (high review) append_props = {} if TARGET_FILE_SIZE_PROPERTY in have else {k: v for k, v in LAYOUT_PROPERTIES.items() if k not in have} layout_via = "duckdb" if append_props else "existing" if rg_set: append_props.update(rg_props) if append_props: setup_statements = [layout_properties_call(alias, args.namespace, args.name, append_props)] def drop_row_group_property(): """Remove the row-group property this import set (once; best effort, never an exit). Left on the table, every plain DuckDB INSERT into it would fail, so a failed removal is a warning naming the command that removes it.""" nonlocal rg_state if not rg_applied or rg_state is not None: return st, _ = request_status(args, "PATCH", "/v1/table", {"catalog_id": wid, "namespace": args.namespace, "name": args.name, "remove": [SPATIAL_ROW_GROUP_PROPERTY]}) if st < 400: rg_state = "set_then_removed" return rg_state = "removal_failed" print("warning: could not remove the table property %s (HTTP %d); while it is set, a plain DuckDB INSERT into the table " "fails. Remove it: lhbox table set-properties %s.%s --catalog %s --remove %s" % (SPATIAL_ROW_GROUP_PROPERTY, st, args.namespace, args.name, wid, SPATIAL_ROW_GROUP_PROPERTY), file=sys.stderr) if path != "api_create_then_insert" and geometry_cols and fv == 2: print("note: geometry column(s) %s written as WKB binary (format version 2 has no geometry type); geo.encoding says so" % ", ".join(geometry_cols), file=sys.stderr) print("importing %d file(s) into %s.%s as ONE commit (%s%s)…" % (len(files), args.namespace, args.name, path, (", rows ordered by %s" % order_col) if order_col else ""), file=sys.stderr) t0 = time.time() # a setup failure AFTER the table was created (by the API, or DuckDB's CREATE TABLE, the first setup statement of the # v2 create path) leaves it empty: a `--mode create` re-run answers table_exists, so the remedy says what does work created = path == "api_create_then_insert" rg_applied = rg_set and created # POST /v1/tables carried it def created_remedy(): return ("The table %s.%s was created, empty, before this failed. Fix the cause, then re-run with --mode append and " "without --format-version (a --mode create re-run answers table_exists), or drop it: lhbox table delete " "%s.%s --catalog %s." % (args.namespace, args.name, args.namespace, args.name, wid)) try: if not rgr: # the PyIceberg runner attaches nothing engine.session(session) for i, st in enumerate(setup_statements): engine.run(st, attached=True) if i == 0 and path == "duckdb_create_then_insert": created = True if rg_set and SPATIAL_ROW_GROUP_PROPERTY in st: rg_applied = True except Exception as exc: # noqa: BLE001 - DuckDB's own error classes drop_row_group_property() if created and args.mode == "create": # a re-run unchanged answers table_exists: the outcome is not "failed" (safe to retry) whatever the class _duckdb_die(exc, table_created=True, rows_written=0, outcome="unknown", remedy=created_remedy()) _duckdb_die(exc) try: if rgr: pyi_answer = pyiceberg_append(pyi_exe, rec, args, "SELECT %s FROM %s" % (", ".join(exprs), source), order_col if order_expr else None, files if fmt == "parquet" else [], pyi_props) else: if setup_statements and hasattr(engine, "refresh"): engine.refresh() # the properties just set must reach the writer engine.run(statement, attached=True) except ImportNotCommitted as exc: # the runner failed before its commit: nothing landed if created and args.mode == "create": _duckdb_die(exc, committed=False, table_created=True, rows_written=0, outcome="unknown", remedy=created_remedy()) _duckdb_die(exc, committed=False, outcome="failed", remedy="Nothing was committed%s; fix the cause and run the same import again." % ("" if args.mode == "append" else " and the table was not created")) except Exception as exc: # noqa: BLE001 - the data commit: ask the table what happened drop_row_group_property() import_insert_failed(args, q, before, exc, created_remedy=created_remedy() if created and args.mode == "create" else None) drop_row_group_property() seconds = round(time.time() - t0, 2) properties_set, properties_error = [], None if geo_props: # the data is in the table by now: a refused property update is a warning in the report, never an exit # (a retry of the whole import would append the rows twice); the live API before PATCH /v1/table was # deployed answered 405 here (2026-09-21) st, upd = request_status(args, "PATCH", "/v1/table", {"catalog_id": wid, "namespace": args.namespace, "name": args.name, "properties": geo_props}) if st < 400: properties_set = upd.get("set", sorted(geo_props)) else: err = (upd.get("error") or {}) if isinstance(upd, dict) else {} properties_error = {"status": st, "code": err.get("code") or ("http_%d" % st), "message": err.get("message") or (upd.get("detail") if isinstance(upd, dict) else None) or str(upd)[:300]} print("warning: the rows are in, but the geo.* properties could not be set (HTTP %d %s); set them later with " "lhbox table set-properties" % (st, properties_error["message"]), file=sys.stderr) after = request(args, "GET", "/v1/table?" + q) # its v3 warning was printed once already at the create out = { "table": after.get("table"), "warehouse": after.get("warehouse"), "warehouse_id": _cid(after), "mode": args.mode, "path": path, "format": fmt, "files": len(files), "bytes": _bytes_of(files), "seconds": seconds, "columns": len(order), "rows": _rows_appended(before, after), "rows_total": after.get("rows"), "commits": (after.get("snapshots") or 0) - (before.get("snapshots") or 0), "snapshots": after.get("snapshots"), "format_version": after.get("format_version"), "format_version_source": fv_source, "geometry_columns": geometry_cols, "properties_set": properties_set, "properties": after.get("properties") or {}, "casts": casts, # --row-group-rows: the PyIceberg write (research/90) "row_group_rows": rgr, "writer": ("pyiceberg %s" % pyi_found.get("pyiceberg")) if rgr else "duckdb", "data_files": pyi_answer.get("files") if rgr else None, "writer_peak_rss_bytes": pyi_answer.get("peak_rss_bytes") if rgr else None, "duckdb": engine.where, "geoparquet_files": len(geo_by_file), # the layout (platform/docs/performance.md): the order column and where it came from, the target file size and # how it got onto the table (duckdb: CALL set_iceberg_table_properties; api: POST /v1/tables; existing: it had one) "order_by": order_col, "order_by_source": order_source, "layout": {TARGET_FILE_SIZE_PROPERTY: (after.get("properties") or {}).get(TARGET_FILE_SIZE_PROPERTY), CODEC_PROPERTY: (after.get("properties") or {}).get(CODEC_PROPERTY), "set_via": layout_via}, # a geometry import's layout (research/49a §5); `temporary` = DuckDB 1.5 workarounds that go when DuckDB catches up "spatial_layout": ({"temporary": True, "note": SPATIAL_LAYOUT_NOTE, "geometry_column": primary_geom, "hilbert_order": order_source == "default_spatial", "threads": 1, "row_group_bytes": int(SPATIAL_ROW_GROUP_BYTES) if rg_applied else None, "row_group_property": rg_state or ("not_applied" if rg_set else None), "bbox_columns_filled": list(BBOX_COLUMNS) if bbox_active else []} if spatial else None), } if getattr(args, "full", False): out["statement"] = statement # every column name and every file path: on request, not by default out["setup_statements"] = setup_statements if properties_error: out["properties_error"] = properties_error out["geo_properties_wanted"] = geo_props if created_via_api is not None: out["created_via_api"] = {k: created_via_api.get(k) for k in ("format_version", "format_version_source", "table_uuid")} catalog = after.get("warehouse") if after.get("warehouse") and CATALOG_NAME_RE.match(str(after.get("warehouse"))) else wid if not after.get("doc"): # #1997: a table nobody described leaves the next reader to rediscover it by querying; agents follow what a # command answers, so the answer names what finishes the load (from what is already here: no further call) ref = "%s.%s.%s" % (catalog, args.namespace, args.name) out["next_step"] = { "document": 'lhbox table document %s --doc "One row per …, from …" --column ="…"' % ref, "agents_md": "lhbox catalog agents-md %s (none yet? write one: --set AGENTS.md; where to start, structure, " "joins, caveats, freshness, attribution)" % catalog} if _want_json(args): print_json(out) return print("%s: %s from %d %s file(s)%s in %s s, %d commit(s) (%s snapshot(s) now), %d columns, format-version %s; path %s%s" % (out["table"], "rows" if out["rows"] is None else "%s rows" % out["rows"], out["files"], fmt, (" (%s)" % fmt_bytes(out["bytes"])) if out["bytes"] is not None else "", seconds, out["commits"], out["snapshots"], out["columns"], out["format_version"], path, ("; rows ordered by %s (%s)" % (order_col, order_source) if order_col else "") + ("" if rgr else (", files at 128 MB" if order_col else "; files at 128 MB")))) if out["rows"] is None: print(ROWS_NOT_AVAILABLE) if rgr: print("row groups of %d row(s) in %s data file(s) of up to %s, written by pyarrow and registered by %s; writer peak %s" % (rgr, out["data_files"], fmt_bytes(ROW_GROUP_FILE_BYTES), out["writer"], fmt_bytes(out["writer_peak_rss_bytes"] or 0))) if geometry_cols: print("geometry: %s; geo properties set: %s" % (", ".join(geometry_cols), ", ".join(properties_set) or "none (not GeoParquet)")) if spatial: sl = out["spatial_layout"] print("spatial layout (temporary DuckDB workarounds): %s, 1 writer thread%s%s" % ("Hilbert order of %s" % primary_geom if sl["hilbert_order"] else "order: %s" % (order_col or "the files' own"), ", 8 MB row groups" if sl["row_group_bytes"] else "", ", the table's bbox columns filled" if sl["bbox_columns_filled"] else "")) print("query it with: WHERE %s && AND ST_Intersects(%s, ) (DuckDB skips files and row groups for && only)" % (sql_ident(primary_geom), sql_ident(primary_geom))) print("check: lhbox table get %s.%s --catalog %s" % (args.namespace, args.name, catalog)) if out.get("next_step"): print("next: describe it for the next reader: %s" % out["next_step"]["document"]) print(" and the catalog's notes: %s" % out["next_step"]["agents_md"]) def persistent_secret_statements(f): """CREATE OR REPLACE PERSISTENT SECRET for the catalog and for its buckets (scoped to them, so two catalogs' secrets coexist), from recipe_fields() -- never from parsing the recipe's SQL. Not for the public reader. Each scope ends in `/` (#2616): DuckDB picks the longest matching scope, and `s3://acme--sales` also matched catalog sales_eu's buckets (`s3://acme--sales-eu/`, `s3://acme--sales-eu--blobs/`), whose files were then read with sales's key.""" name = "lhbox_" + f["alias"] return [ "INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;", "CREATE OR REPLACE PERSISTENT SECRET %s (TYPE ICEBERG, CLIENT_ID %s, CLIENT_SECRET %s, OAUTH2_SERVER_URI %s);" % (name, sql_str(f["client_id"]), sql_str(f["client_secret"]), sql_str(f["oauth"])), "CREATE OR REPLACE PERSISTENT SECRET %s (TYPE S3, KEY_ID %s, SECRET %s, ENDPOINT %s, URL_STYLE 'path', USE_SSL %s, " "REGION 'us-east-1', SCOPE %s);" % (persistent_s3_secret_name(f["alias"]), sql_str(f["client_id"]), sql_str(f["client_secret"]), sql_str(f["storage_host"]), f["use_ssl"], "[%s]" % ", ".join(sql_str(x) for x in _persist_scopes(f))), ], name def persistent_s3_secret_name(alias): """The storage secret of `--persist`. Not lhbox__s3 (#2945): a catalog may be named _s3, and its ICEBERG secret lhbox__s3 then WAS catalog 's S3 secret, each persist replacing the other's. No alias yields a name starting lhboxs3_, so the two kinds never meet.""" return "lhboxs3_" + alias def _persist_scopes(f): return ["s3://%s/" % f["bucket"]] + (["s3://%s/" % f["blob_bucket"]] if f.get("blob_bucket") else []) def _persist_legacy_secrets(engine, f, name): """Before --persist writes (#2945): the S3 secret a CLI before 0.6.158 named lhbox__s3. One named like THIS catalog's ICEBERG secret is another catalog's (alias _s3 minus the suffix): replacing it would take that catalog's storage away, so refuse. Returns this catalog's own old S3 secret (scoped to its buckets only), which the caller drops once the new one is written, or None.""" legacy = name + "_s3" rows = engine.run("SELECT name, type, scope FROM duckdb_secrets() WHERE name IN (%s, %s)" % (sql_str(name), sql_str(legacy))) mine = {s.rstrip("/") for s in _persist_scopes(f)} own = None for r in rows or []: scope = r.get("scope") scope = scope if isinstance(scope, list) else [scope] if scope else [] if str(r.get("type")).lower() != "s3": continue if r.get("name") == name: other = name[len("lhbox_"):-len("_s3")] if name.endswith("_s3") else None die_json("secret_name_taken", "DuckDB already holds a persistent S3 secret named %s%s; writing this catalog's catalog secret under " "that name would replace it. Nothing was written." % (name, " (catalog %s's storage secret, from an " "older lhbox)" % other if other else ""), EXIT_LIMIT, secret=name, remedy=("lhbox duckdb --persist --catalog %s first (it moves that catalog's storage secret to %s), " "then run this again; or DROP PERSISTENT SECRET %s; if you no longer use it." % (other, persistent_s3_secret_name(other), name)) if other else "DROP PERSISTENT SECRET %s; if you no longer use it, then run this again." % name) elif r.get("name") == legacy and scope and {str(s).rstrip("/") for s in scope} <= mine: own = legacy return own def attach_line(f, secret="lhbox", version=None, delegation=None): """The ATTACH of a catalog, from recipe_fields(); `version` as in recipe_session(); `delegation` 'none' for Edge reads (DuckDB then reads with the S3 secret, not a vended session).""" extra = ", ACCESS_DELEGATION_MODE 'none'" if delegation == "none" else "" return "ATTACH %s AS %s (TYPE ICEBERG, %s %s, SECRET %s%s);" % (sql_str(f["bucket"]), f["alias"], attach_uri_option(version), sql_str(f["uri"]), secret, extra) # the control plane's own rules (HANDLE_RE, WAREHOUSE_NAME_RE): a name outside them never becomes a request path PUBLIC_CATALOG_RE = re.compile(r"^([a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])?)/([a-z][a-z0-9_]{0,62})$") def public_catalog_rec(args, ref): """research/38: `--catalog /` names a PUBLIC catalog of any organisation. Its read-only recipe comes from GET /v1/public///connection (the public-reader key, shared by every reader), reshaped into the fields the shell path reads.""" m = PUBLIC_CATALOG_RE.match(ref) if not m: die_json("invalid_value", "A public catalog is named /, e.g. commons/pubdata.", EXIT_USAGE, field="catalog", got=ref, remedy="The organisation's handle and the catalog's name, separated by one slash.") handle, name = m.group(1), m.group(2) pub = request(args, "GET", "/v1/public/%s/%s/connection" % (urllib.parse.quote(handle, safe=""), urllib.parse.quote(name, safe="")), timeout=90) return {"json": {"catalog": "%s/%s" % (handle, name), "read_only": True, "bucket": pub.get("bucket"), "catalog_alias": pub.get("catalog_alias"), "catalog_uri": pub.get("catalog_uri"), "sql": pub.get("duckdb_sql"), "tables": pub.get("tables"), "note": pub.get("note")}, "sql": pub.get("duckdb_sql"), "warehouse_name": pub.get("bucket"), "catalog_alias": pub.get("catalog_alias"), "_public_reader": True, "catalog_uri": pub.get("catalog_uri"), "catalog_credential": pub.get("catalog_credential"), "public_url": pub.get("public_url"), "level": "read (public)", "identity": "the public reader", "notes": [pub.get("note")] if pub.get("note") else []} def cmd_duckdb(args): ref = catalog_arg(args) or "" if getattr(args, "credential_process", False) and (not getattr(args, "edge", False) or "/" in ref or args.persist): # one JSON document or a usage error, never a shell: DuckDB runs this as its credential_process (high review of # #1883, finding 8) die_json("credential_process_needs_edge", "--credential-process answers for your own catalog's edge credential only.", EXIT_USAGE, remedy="lhbox duckdb --catalog --edge --credential-process (DuckDB runs it itself; you need not)") if "/" in ref: # /: another organisation's PUBLIC catalog (research/38) if getattr(args, "edge", False): die_json("edge_reads_public", "--edge is for your own catalogs: a public catalog is already read through the CDN.", EXIT_USAGE, remedy="lhbox duckdb --catalog %s (without --edge)" % ref) if args.persist: die_json("public_catalog_not_persisted", "--persist is for your own catalogs: a public catalog's reader key is " "shared and changes when its owner unpublishes, so it is fetched each time.", EXIT_ERROR, remedy="lhbox duckdb --catalog %s (without --persist)" % ref) rec = public_catalog_rec(args, ref) else: wid = resolve_catalog(args) params = {"catalog_id": wid, "engine": "duckdb"} if getattr(args, "edge", False) and getattr(args, "no_edge", False): die_json("edge_flags_conflict", "--edge and --no-edge ask for opposite things.", EXIT_USAGE, remedy="Keep one: --edge (through the CDN) or --no-edge (from the storage).") if getattr(args, "edge", False): if args.persist: die_json("edge_not_persisted", "--edge is not persisted: an edge credential lives an hour, so it is fetched " "each time.", EXIT_USAGE, remedy="lhbox duckdb --edge (without --persist)") params.update(level="read", edge="true") # Edge reads: the read recipe through the CDN (docs/edge-reads.md) elif args.persist: # a persisted secret outlives an edge credential's hour: the store's recipe, even for a catalog with edge caching params["edge"] = "false" elif getattr(args, "no_edge", False): params["edge"] = "false" # the storage, even where the catalog has edge caching else: # edge caching: a catalog an admin opted in answers its read recipe through the CDN when this shell can renew # the hour-long credential (a KNOWN DuckDB 1.5.5+, the key not given as --api-key), decided before asking so # nothing is minted for nothing (second and third high reviews of #1899). edge_auto, not edge=auto: a control # plane from before it ignores the parameter # probed without exiting: a missing or unreadable binary means "do not ask", and the shell's own check below # reports it after the API has answered (an access refusal first, as before) exe = shutil.which("duckdb") if edge_renewal_possible(args, _version_of([exe, "--version"])[0] if exe else None): params["edge_auto"] = "1" rec = request(args, "GET", "/v1/connection?" + urllib.parse.urlencode(params), timeout=90) if getattr(args, "credential_process", False): # DuckDB's credential_process (edge_credential_config): one fresh edge credential on stdout, nothing else print(json.dumps(edge_process_credential(rec, files=getattr(args, "edge_files", False)))) return if wants_catalog_token(rec) and not (args.persist and rec.get("credentials") != "vended_only"): # namespace or table grants: the shell attaches with a catalog token (a scoped member's --persist keeps its pair: # a persisted bearer would be dead within the hour); a member whose token the route refuses keeps its pair _duckdb_with_catalog_token(args, rec) rec = _require_static_recipe(rec, "duckdb") fields = recipe_fields(rec) # every field checked before any of them reaches DuckDB (L6) alias = fields["alias"] if args.persist: engine = duckdb_engine(args) statements, secret = persistent_secret_statements(fields) s3_secret = persistent_s3_secret_name(alias) try: engine.run(statements[0]) legacy = _persist_legacy_secrets(engine, fields, secret) for st in statements[1:]: engine.run(st) if legacy: # this catalog's own S3 secret under the old name engine.run("DROP PERSISTENT SECRET %s;" % legacy) rows = engine.run("SELECT current_setting('secret_directory') AS dir") except Exception as exc: # noqa: BLE001 - DuckDB's own error classes _duckdb_die(exc) secret_dir = (rows[0].get("dir") if rows else None) or os.path.expanduser("~/.duckdb/stored_secrets") written = [] # its own two files by name: `secret*` also matched another catalog's (lhbox_sales_eu for lhbox_sales, #2616) for f in sorted(glob.glob(os.path.join(secret_dir, glob.escape(secret) + ".*")) + glob.glob(os.path.join(secret_dir, glob.escape(s3_secret) + ".*"))): try: os.chmod(f, 0o600) except OSError: pass written.append(f) line = attach_line(fields, secret) out = {"attach": line, "catalog_alias": alias, "secrets": [secret, s3_secret], "secret_directory": secret_dir, "files": written, "level": rec.get("level"), "identity": rec.get("identity"), "duckdb": engine.where, "note": "The two persistent secrets hold the catalog credential (client id and secret; the same pair is the S3 " "key) on disk in DuckDB's secret directory, 0600, readable by any DuckDB this user runs. Rotate the " "catalog (lhbox catalog rotate%s) or DROP PERSISTENT SECRET %s; DROP PERSISTENT SECRET %s; to revoke." % (", once a person has claimed this catalog with lhbox claim" if _unclaimed_in_use(args) else "", secret, s3_secret)} if _want_json(args): print_json(out) return print("# persistent secrets %s and %s written to %s (level %s); in any DuckDB session on this machine:" % (secret, s3_secret, secret_dir, rec.get("level"))) print("INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs;") print(line) print("# %s" % out["note"], file=sys.stderr) return exe, version = _duckdb_shell_exe(args) print("Attaching %s AS %s (level %s, identity %s). Tables: SHOW ALL TABLES; e.g. SELECT * FROM %s..
LIMIT 10;" % (rec.get("warehouse_name"), alias, rec.get("level"), rec.get("identity"), alias), file=sys.stderr) for note in rec.get("notes", [])[:1]: print("note: " + note, file=sys.stderr) _print_scoped(rec, alias) if fields.get("edge") and not edge_renewal_possible(args, version): print("note: this shell's edge credential is not renewed: it expires at %s (open a new lhbox duckdb then)%s" % ((rec.get("edge_reads") or {}).get("expires_at"), "; a key given as --api-key is never put in DuckDB's " "environment, so use LHBOX_API_KEY or lhbox login to have it renewed" if getattr(args, "api_key", None) else "; DuckDB 1.5.5 or newer renews it"), file=sys.stderr) elif fields.get("edge"): # Edge reads: DuckDB renews the hour-long edge credential itself while the shell runs (edge_credential_config) cfg_dir, env = edge_credential_config(args, rec.get("warehouse_id") or wid) try: rc = run_duckdb_with_init(exe, "\n".join(recipe_session(rec, version, edge_profile=EDGE_PROFILE)) + "\n", _duckdb_extra(args), env=env) finally: shutil.rmtree(cfg_dir, ignore_errors=True) sys.exit(rc) sys.exit(run_duckdb_with_init(exe, "\n".join(recipe_session(rec, version)) + "\n", _duckdb_extra(args))) def _duckdb_shell_exe(args): """(path, version or None) of the duckdb binary the shell runs (or exit): on PATH, 1.0 or newer, a warning below 1.5.5.""" exe = shutil.which("duckdb") if not exe: # the remedy fits this machine (#1759: `brew` was offered on Linux, and an agent that had just installed the # python module, as doctor advises, was not told that module already works through --persist) install = ("brew install duckdb" if sys.platform == "darwin" else "winget install DuckDB.cli" if os.name == "nt" else "curl https://install.duckdb.org | sh, or pip install duckdb-cli") modules = [w for w, v, _ in duckdb_versions() if w.startswith("python module") and v >= DUCKDB_MIN] if modules: remedy = ("DuckDB is here as a %s: `lhbox duckdb --persist` writes the catalog's secrets for it, then run " "the ATTACH line it prints in python (`lhbox table import` uses the module too). For the " "interactive shell: %s (https://duckdb.org/install), then lhbox duckdb again." % (modules[0], install)) else: remedy = ("%s (https://duckdb.org/install), then run lhbox duckdb again; or `pip install 'duckdb>=%s'` and " "`lhbox duckdb --persist`, which writes DuckDB secrets so a bare ATTACH works from python." % (install, _dotted(DUCKDB_MIN))) die_json("duckdb_binary_not_found", "The interactive shell needs the `duckdb` binary on PATH; none found.", EXIT_ERROR, remedy=remedy) v, raw = _version_of([exe, "--version"]) if v and v < DUCKDB_SHELL_FLOOR: # a DuckDB before 1.0 has no CREATE SECRET and no Iceberg REST attach: it cannot open the catalog, and its parse # errors print the start of each failing recipe line, credential included (the recorded run of 2026-10-12) die_json("duckdb_too_old", "The duckdb binary on PATH is %s (%s): it cannot attach an Iceberg catalog." % (_dotted(v), exe), EXIT_ERROR, found=raw, needed=_dotted(DUCKDB_MIN), remedy="%s, then run lhbox duckdb again; or put a newer duckdb first on PATH." % _upgrade_hint("duckdb binary via " + exe)) if v and v < DUCKDB_MIN and not getattr(args, "no_version_check", False): print(duckdb_version_warning([("duckdb binary via " + exe, v, raw)]), file=sys.stderr) return exe, v def _duckdb_extra(args): extra = list(args.duckdb_args or []) if extra and extra[0] == "--": # argparse.REMAINDER keeps the separator; duckdb would choke on it (measured) extra = extra[1:] return extra def _print_scoped(rec, alias): """The namespaces and tables a scoped holder reaches, by name, on stderr (SHOW ALL TABLES lists none of them).""" for n in rec.get("namespaces") or []: # namespace grants: these namespaces only, reached by name (research/45: listing namespaces is refused to them) print("namespace %s (%s): %s" % (n.get("namespace"), n.get("level"), ", ".join("%s.%s.%s" % (alias, n.get("namespace"), t) for t in n.get("tables") or []) or "no tables yet"), file=sys.stderr) for t in rec.get("tables") or []: # table grants: these tables only, by name (SHOW ALL TABLES lists none of them) print("table %s.%s.%s (%s)" % (alias, t.get("namespace"), t.get("table"), t.get("level")), file=sys.stderr) def _duckdb_with_catalog_token(args, rec): """`lhbox duckdb` for a holder of namespace or table grants: the shell attaches with a catalog token served by a CatalogTokenBroker on loopback for the shell's life (renewed before each expiry), never with a key pair. A service account's --persist is refused: a persisted bearer would be dead within the hour.""" if args.persist: die_json("persist_not_offered", "--persist writes a static key pair, and this identity reaches the catalog through " "namespace or table grants with a catalog token of about an hour: there is nothing lasting to persist.", EXIT_ERROR, catalog=rec.get("warehouse_id"), remedy="lhbox duckdb (the shell renews the token itself), or lhbox connect for the token and its samples.") wid = rec.get("warehouse_id") exe, version = _duckdb_shell_exe(args) if rec.get("credentials") == "vended_only": ans = mint_catalog_token(args, wid) # no other way in: a refusal is the route's envelope else: try: with _quiet(): ans = mint_catalog_token(args, wid) except _Refused as r: code = ((r.parsed or {}).get("error") or {}).get("code") if isinstance(r.parsed, dict) else None if code in CATALOG_TOKEN_FALLBACK: # a member's own pair recipe still works: the shell opens with it (high review of #1488, 2) print("note: no catalog token (%s); attaching with your own key pair instead" % code, file=sys.stderr) return None _fail("POST", "/v1/catalog-token", r.status, r.parsed) f = _checked_catalog_token(ans) raw = (_env("CATALOG_TOKEN_RENEW_BEFORE") or "").strip() renew = int(raw) if raw.isascii() and raw.isdigit() else None # a test aid (CatalogTokenBroker); unset in use raw = (_env("TEST_CATALOG_TOKEN_MIN_LIFE") or "").strip() floor = int(raw) if raw.isascii() and raw.isdigit() else None # a test aid too; the broker honours it only with renew broker = CatalogTokenBroker(lambda: quiet_catalog_mint(args, wid), first=f, renew_before=renew, min_life=floor).start() print("Attaching %s AS %s (level %s via %s, identity %s) with a catalog token: the catalog vends each table's storage " "session; lhbox renews the token while this shell runs. e.g. SELECT * FROM %s..
LIMIT 10;" % (f["bucket"], f["alias"], ans.get("level"), ans.get("level_via"), ans.get("identity"), f["alias"]), file=sys.stderr) _print_scoped(ans, f["alias"]) try: rc = run_duckdb_with_init(exe, "\n".join(token_session(f, broker.token_uri, broker.client_id, broker.client_secret, version)) + "\n", _duckdb_extra(args)) finally: broker.stop() said = broker.outcome() if said: print(said, file=sys.stderr) sys.exit(rc) def duckdb_proxy(environ=None): """(init lines, environment) that hand DuckDB an authenticated proxy it cannot read itself (#3807): DuckDB takes HTTP_PROXY from the environment but fails every request when it carries a user and password ("Failed to parse http_proxy 'http://user:pass@localhost:3128' into a host and port", measured with 2.0; agent sandboxes such as Claude Cowork reach the network only that way). The URL is split here: host:port, and the URL-decoded user and password through DuckDB's own settings, which win over the environment (measured 1.5.6 and 2.0). The password only ever travels in the init file (a 0600 FIFO), never argv or the terminal. The loopback addresses join NO_PROXY: the catalog-token broker listens there, and DuckDB honours NO_PROXY. ([], None) when there is nothing to change.""" environ = os.environ if environ is None else environ raw = next((environ[k] for k in ("HTTP_PROXY", "http_proxy") if environ.get(k)), "") u = urllib.parse.urlsplit(raw if "://" in raw else "http://" + raw) try: host, port = u.hostname, u.port except ValueError: return [], None if not host or u.username is None: return [], None # no credentials: DuckDB reads it as it is q = lambda v: "'%s'" % v.replace("'", "''") lines = ["SET http_proxy=%s;" % q(("[%s]" % host if ":" in host else host) + (":%d" % port if port else "")), "SET http_proxy_username=%s;" % q(urllib.parse.unquote(u.username))] if u.password is not None: lines.append("SET http_proxy_password=%s;" % q(urllib.parse.unquote(u.password))) env = dict(environ) for k in ("NO_PROXY", "no_proxy"): have = [h for h in (env.get(k) or "").split(",") if h.strip()] env[k] = ",".join(have + [h for h in ("127.0.0.1", "localhost", "::1") if h not in have]) return lines, env def run_duckdb_with_init(exe, init_sql, extra_args, open_timeout=30.0, env=None): """Start `duckdb -init ` and hand the terminal over; the recipe never touches argv. The init path is a 0600 FIFO in a fresh private directory: the write side only opens once duckdb has opened it to read, so the SQL is written exactly then and the FIFO is removed at once -- nothing to race, nothing left on disk during the session. Where mkfifo is missing (Windows) a 0600 regular file is used and removed after a moment (the open fd survives the unlink). Returns duckdb's exit code. The session runs quietly (quiet_init).""" proxy, proxy_env = duckdb_proxy(env) if proxy: init_sql = "\n".join(proxy) + "\n" + init_sql env = proxy_env init_sql = quiet_init(init_sql) tmpdir = tempfile.mkdtemp(prefix="lhbox-duckdb-") init = os.path.join(tmpdir, "init.sql") fifo = hasattr(os, "mkfifo") if fifo: os.mkfifo(init, 0o600) else: fd = os.open(init, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w") as fh: fh.write(init_sql) rc = 1 restore = None try: proc = subprocess.Popen([exe, "-init", init] + list(extra_args), **({"env": env} if env is not None else {})) restore = _ignore_ctrl_c() # from here the terminal's Ctrl-C belongs to DuckDB (#1931) if fifo: deadline = time.time() + open_timeout wfd = None while wfd is None and proc.poll() is None and time.time() < deadline: try: wfd = os.open(init, os.O_WRONLY | os.O_NONBLOCK) # ENXIO until duckdb has it open to read except OSError: time.sleep(0.02) if wfd is not None: os.set_blocking(wfd, True) try: os.write(wfd, init_sql.encode()) finally: os.close(wfd) else: time.sleep(1.0) _remove_quietly(init, tmpdir) rc = proc.wait() finally: if restore: restore() _remove_quietly(init, tmpdir) return rc def _ignore_ctrl_c(): """Ignore SIGINT in lhbox while the terminal belongs to a child (#1931) -> a function that restores it, or None. Ctrl-C reaches the whole foreground process group, and DuckDB's shell uses it to cancel a query and carries on; lhbox dying of it handed the terminal back to the user's shell with DuckDB still running and took its credentials (the edge config, the token endpoint) with it. Called AFTER the child started: an ignored signal survives exec, a handled one does not, so DuckDB keeps its own Ctrl-C. The child's exit code stays lhbox's.""" try: old = signal.signal(signal.SIGINT, signal.SIG_IGN) except ValueError: # not the main thread: nothing to change return None return lambda: signal.signal(signal.SIGINT, old if old is not None else signal.default_int_handler) def quiet_init(init_sql, tty=None): """The init file with its own output discarded: the shell otherwise prints a `Success: true` table for each CREATE SECRET ahead of the first query, which an agent reads (and pays for) as if it were an answer. Errors still reach stderr, and DuckDB stops at the first one. Off a terminal (an agent, a pipe) also `.startup_text none`: no "-- Loading resources from " line and, on DuckDB 2.0, no agent-mode banner; agent mode itself stays on. Both commands work from DuckDB 1.0 on (measured 2026-10-22 with 1.5.5 and 2.0.0).""" if tty is None: tty = sys.stdout.isatty() if not init_sql.endswith("\n"): init_sql += "\n" # a dot command must start its own line return ("" if tty else ".startup_text none\n") + ".output %s\n" % os.devnull + init_sql + ".output\n" def _remove_quietly(path, directory): for fn in (lambda: os.unlink(path), lambda: os.rmdir(directory)): try: fn() except OSError: pass # ---------------------------------------------------------------- doctor: the whole path, nothing written def _sigv4_headers(method, url, access_key, secret_key, session_token=None, region="us-east-1", service="s3", payload=b"", extra=None): """AWS Signature Version 4, stdlib only. Signs host, x-amz-content-sha256 and x-amz-date (plus the session token when there is one, and every header in `extra`, e.g. x-amz-copy-source) over `payload` (empty: HEAD, GET, DELETE, a CopyObject PUT). Its source is also embedded in `table add-files`' runner (_ADD_FILES_RUNNER): imports inside.""" import datetime, hashlib, hmac, urllib.parse u = urllib.parse.urlsplit(url) now = datetime.datetime.now(datetime.timezone.utc) amz_date, day = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d") payload_hash = hashlib.sha256(payload or b"").hexdigest() headers = {"host": u.netloc, "x-amz-content-sha256": payload_hash, "x-amz-date": amz_date} if session_token: headers["x-amz-security-token"] = session_token for k, v in (extra or {}).items(): headers[k.lower()] = v signed = ";".join(sorted(headers)) canonical_headers = "".join("%s:%s\n" % (k, headers[k].strip()) for k in sorted(headers)) query = sorted(urllib.parse.parse_qsl(u.query, keep_blank_values=True)) canonical_query = "&".join("%s=%s" % (urllib.parse.quote(k, safe="-_.~"), urllib.parse.quote(v, safe="-_.~")) for k, v in query) # the URL's path is already on the wire encoded (s3_call quotes the key): encode it ONCE, or a key with a space, an = # or an accent signs as %2520/%253D and the store answers SignatureDoesNotMatch (add-files' staged deletes, 2026-10-22) canonical_uri = urllib.parse.quote(urllib.parse.unquote(u.path or "/"), safe="/-_.~") canonical = "\n".join([method, canonical_uri, canonical_query, canonical_headers, signed, payload_hash]) scope = "%s/%s/%s/aws4_request" % (day, region, service) to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canonical.encode()).hexdigest()]) key = ("AWS4" + secret_key).encode() for part in (day, region, service, "aws4_request"): key = hmac.new(key, part.encode(), hashlib.sha256).digest() signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest() out = {k: v for k, v in headers.items() if k != "host"} out["Authorization"] = "AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s" % (access_key, scope, signed, signature) return out USER_AGENT = "lhbox/%s (python %d.%d; %s)" % (__version__, sys.version_info[0], sys.version_info[1], sys.platform) def _install_user_agent(): """Every request names this lhbox (`User-Agent: lhbox/ ...`), so the API can tell which versions are in use and answer an old one with a hint its own errors carry (feedback 2026-10-16, item 3). A header a call sets wins. The opener is built once per process for the environment it reads when built (the proxies, and the CA bundle its TLS context loads): building one makes a TLS context and reads the system's CAs, 5 ms each time main() ran. Until the first request a stand-in is installed that builds it then (perf: lhbox-tls-context-every-run): a command that sends nothing (`lhbox mcp headers` at every MCP connection, `mcp run`, --help) never pays for it.""" key = tuple(sorted((k, v) for k, v in os.environ.items() if k.lower().endswith("_proxy") or k.startswith("SSL_CERT_"))) opener = _OPENER.get(key) urllib.request.install_opener(opener if opener is not None else _LazyOpener(key)) def _built_opener(key): opener = _OPENER.get(key) if opener is None: opener = urllib.request.build_opener() opener.addheaders = [("User-Agent", USER_AGENT)] _OPENER.clear() _OPENER[key] = opener return opener class _LazyOpener: """urlopen() calls only `open` on the installed opener: the first call builds the real one, installs it, uses it.""" def __init__(self, key): self._key = key def open(self, *a, **kw): opener = _built_opener(self._key) urllib.request.install_opener(opener) return opener.open(*a, **kw) _OPENER = {} class _NoRedirect(urllib.request.HTTPRedirectHandler): """A 3xx is answered as it is (an HTTPError the caller sees as its status), never followed.""" def redirect_request(self, req, fp, code, msg, headers, newurl): return None def _http(method, url, headers=None, data=None, timeout=30, redirects=True): """(status, body bytes, headers) without exceptions for HTTP errors; (0, reason, {}) when unreachable. An Authorization header is never carried across a redirect (security review 2026-10-08, L7); redirects=False follows none at all (`lhbox update` runs only a script it fetched from the site it named, L5).""" req = urllib.request.Request(url, data=data, method=method) for k, v in (headers or {}).items(): if k.lower() == "authorization": req.add_unredirected_header(k, v) else: req.add_header(k, v) try: if not redirects and not req.has_header("User-agent"): req.add_header("User-Agent", USER_AGENT) opener = urllib.request.urlopen if redirects else urllib.request.build_opener(_NoRedirect).open with opener(req, timeout=timeout) as r: return r.status, r.read(), dict(r.headers) except urllib.error.HTTPError as e: return e.code, e.read(), dict(e.headers) except urllib.error.URLError as e: return 0, str(e.reason).encode(), {} except (socket.timeout, OSError, http.client.HTTPException) as e: return 0, ("%s: %s" % (type(e).__name__, e)).encode(), {} def _s3_error(body): """AccessDenied out of an S3 error body, or the first 120 characters of it.""" m = re.search(r"([^<]+)", body.decode(errors="replace")) return m.group(1) if m else body.decode(errors="replace")[:120].strip() def s3_bucket_probe(endpoint, bucket, access_key, secret_key, session_token=None): """Two signed requests that change nothing: HEAD on the bucket, then ListObjectsV2 with max-keys=1. Both succeeding proves the signature is right and the bucket policy accepts this identity; nothing is created, written or deleted. -> (ok, detail).""" base = endpoint.rstrip("/") + "/" + bucket st, body, _ = _http("HEAD", base, _sigv4_headers("HEAD", base, access_key, secret_key, session_token)) if st == 0: return False, "storage %s unreachable: %s" % (endpoint, body.decode(errors="replace")) if st >= 400: return False, "HEAD %s -> HTTP %d %s" % (bucket, st, _s3_error(body)) url = base + "?list-type=2&max-keys=1" st, body, _ = _http("GET", url, _sigv4_headers("GET", url, access_key, secret_key, session_token)) if st >= 400 or st == 0: return False, "ListObjectsV2 %s -> HTTP %d %s" % (bucket, st, _s3_error(body)) n = re.search(r"(\d+)", body.decode(errors="replace")) return True, "HEAD and ListObjectsV2(max-keys=1) on %s accepted%s" % (bucket, "; the bucket has objects" if n and n.group(1) != "0" else "; the bucket is empty") WRITE_PROBE_KEY = "_lhbox/_probe/data/probe.parquet" # the only key shape a table bucket accepts: a .txt proves nothing def s3_write_probe(endpoint, bucket, access_key, secret_key): """The real thing `doctor --write-probe` opts into: PUT a 0-byte object at WRITE_PROBE_KEY signed as the recipe's identity, then DELETE it. This is the request the 500 window of 2026-09-20 refused while HEAD and List passed. -> (ok, detail); on failure the detail quotes the store's status and error body verbatim.""" url = endpoint.rstrip("/") + "/" + bucket + "/" + WRITE_PROBE_KEY st, body, _ = _http("PUT", url, _sigv4_headers("PUT", url, access_key, secret_key), data=b"") if st == 0: return False, "storage %s unreachable: %s" % (endpoint, body.decode(errors="replace")) if st >= 300: return False, "PUT %s/%s -> HTTP %d: %s" % (bucket, WRITE_PROBE_KEY, st, body.decode(errors="replace").strip()[:300] or "(empty body)") st, body, _ = _http("DELETE", url, _sigv4_headers("DELETE", url, access_key, secret_key)) if st >= 300 or st == 0: return False, "PUT ok, DELETE %s/%s -> HTTP %d: %s (a 0-byte probe object is left behind)" % ( bucket, WRITE_PROBE_KEY, st, body.decode(errors="replace").strip()[:300] or "(empty body)") return True, "0-byte %s written to %s and deleted as the recipe's identity: the store accepts writes" % (WRITE_PROBE_KEY, bucket) def catalog_read_probe(catalog_uri, warehouse, client_id, client_secret, prefix_hint): """The catalog's own three GETs an engine makes first, with the recipe's credential and no engine: mint the catalog token (POST /v1/oauth/tokens, client_credentials), GET /v1/config?warehouse=…, list the namespaces under the prefix it answers. -> (ok, detail, namespaces).""" form = urllib.parse.urlencode({"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": "catalog"}).encode() st, body, _ = _http("POST", catalog_uri.rstrip("/") + "/v1/oauth/tokens", {"Content-Type": "application/x-www-form-urlencoded"}, form) if st == 0: return False, "catalog %s unreachable: %s" % (catalog_uri, body.decode(errors="replace")), [] try: token = json.loads(body).get("access_token") if st == 200 else None except ValueError: token = None if not token: return False, "POST /v1/oauth/tokens -> HTTP %d: the catalog refused the recipe's credential (%s)" % (st, body.decode(errors="replace")[:120].strip()), [] auth = {"Authorization": "Bearer " + token} st, body, _ = _http("GET", catalog_uri.rstrip("/") + "/v1/config?" + urllib.parse.urlencode({"warehouse": warehouse}), auth) if st != 200: return False, "GET /v1/config?warehouse=%s -> HTTP %d %s" % (warehouse, st, body.decode(errors="replace")[:120].strip()), [] try: cfg = json.loads(body) except ValueError: cfg = {} prefix = (cfg.get("overrides") or {}).get("prefix") or (cfg.get("defaults") or {}).get("prefix") or prefix_hint st, body, _ = _http("GET", "%s/v1/%s/namespaces" % (catalog_uri.rstrip("/"), urllib.parse.quote(prefix, safe="")), auth) if st != 200: return False, "GET /v1/%s/namespaces -> HTTP %d %s" % (prefix, st, body.decode(errors="replace")[:120].strip()), [] try: namespaces = [".".join(n) if isinstance(n, list) else str(n) for n in json.loads(body).get("namespaces") or []] except ValueError: namespaces = [] return True, "catalog token minted; prefix %s; %d namespace%s%s" % ( prefix, len(namespaces), "" if len(namespaces) == 1 else "s", " (" + ", ".join(namespaces[:6]) + (", …" if len(namespaces) > 6 else "") + ")" if namespaces else ""), namespaces def _self_sha256(): """This file's SHA-256: the published cli/lhbox.sha256 is of the same bytes (pip copies them unchanged).""" try: with open(os.path.realpath(__file__), "rb") as fh: return hashlib.sha256(fh.read()).hexdigest() except OSError: return None def cli_build(): """The build `--version` names: the first 12 hex of this file's SHA-256 ("unknown" when unreadable).""" return (_self_sha256() or "unknown")[:12] VERSION_CHECK_TTL = 24 * 3600 # seconds between looks at the published version (cached; a failed look is cached too) VERSION_CHECK_FILE = os.path.join(os.path.dirname(CRED_FILE), "version_check.json") def _published_version_cached(api_url, fetch=True): """The version the site publishes, from a once-a-day cache beside the credentials file; None when unknown. At most one 2 s request a day, a failed one cached too (an offline laptop is not asked on every command); never raises.""" site = cli_site(api_url) if not site: return None try: with open(VERSION_CHECK_FILE) as fh: cached = json.load(fh) except (OSError, ValueError): cached = {} cached = cached if isinstance(cached, dict) else {} entry = cached.get(site) if isinstance(entry, dict) and time.time() - float(entry.get("checked_at") or 0) < VERSION_CHECK_TTL: return entry.get("published") or None if not fetch: return None st, body, _ = _http("GET", site + "/cli/lhbox.version", timeout=2) published = body.decode(errors="replace").strip() if st == 200 else "" if not _parse_version(published): published = "" try: cached[site] = {"checked_at": time.time(), "published": published} os.makedirs(os.path.dirname(VERSION_CHECK_FILE), exist_ok=True) with open(VERSION_CHECK_FILE, "w") as fh: json.dump(cached, fh) except OSError: pass return published or None def _is_outdated(published): theirs, mine = _parse_version(published or ""), _parse_version(__version__) return bool(theirs and mine and theirs > mine) _VCHECK = {"off": False, "said": False, "command": None} # set by run(): --no-version-check on the line; told already; the cmd def _newer_published(fetch=False): """The published version when it is newer than this lhbox, else None. fetch=False reads the day's cache only (every successful command fills it); fetch=True may ask the site once (2 s, cached either way). Never raises; None under LHBOX_NO_VERSION_CHECK or --no-version-check, and inside `lhbox update` (it is the remedy, not the patient).""" try: if _env("NO_VERSION_CHECK") or _VCHECK["off"] or _VCHECK["command"] == "cmd_update": return None published = _published_version_cached(_CURRENT_URL[0], fetch=fetch) return published if _is_outdated(published) else None except Exception: # noqa: BLE001 - a hint never breaks an error return None def _update_command(api_url=None): pip = _pip_upgrade_command() if pip: return pip site = cli_site(api_url or _CURRENT_URL[0]) return "lhbox update" if not site or site == SITE_URL else "lhbox update --site %s" % site def _pip_upgrade_command(): """The command that upgrades this lhbox when pip or pipx installed it (the package `lakehousebox`, #2913), else None (the installer's ~/.local/bin/lhbox, or a checkout): the installer must not write a second copy beside a pip one.""" here = os.path.realpath(__file__) if os.path.basename(here) != "lhbox.py" or os.path.basename(os.path.dirname(here)) not in ("site-packages", "dist-packages"): return None parts = here.replace(os.sep, "/").split("/") if "pipx" in parts and "venvs" in parts: return "pipx upgrade lakehousebox" return "pip install -U lakehousebox" def _shadowing_lhbox_package(): """The path of a package directory `lhbox/` on sys.path, or None (#3754): the PyPI placeholder `lhbox` 0.0.1 installs one, and it shadows this module (`lhbox.py`) for every `import lhbox`, the console scripts of a `lakehousebox` older than 0.6.212 included (they failed with ImportError until it was removed).""" for d in sys.path: init = os.path.join(d or os.getcwd(), "lhbox", "__init__.py") if os.path.isfile(init): return init return None def _note_outdated(err): """A failure is when a person needs to know their lhbox is old (feedback 2026-10-16: an option the docs name, refused by a CLI 46 releases behind, read as "you typed it wrong"): the envelope gains `cli_outdated`, from the cache only.""" if not isinstance(err, dict): return if _env("NO_VERSION_CHECK") or _VCHECK["off"] or _VCHECK["command"] == "cmd_update": err.pop("cli_outdated", None) # the API's hint too: a pinned CI job asked for stable envelopes return if "cli_outdated" in err: # the API said it already: said, so run() does not say it again _VCHECK["said"] = True return published = _newer_published(fetch=False) if published: err["cli_outdated"] = {"version": __version__, "published": published, "remedy": _update_command()} _VCHECK["said"] = True def version_notice(args): """One stderr line after a successful command when the site publishes a newer lhbox. Never blocks (2 s, once a day), never fails a command, silent under LHBOX_NO_VERSION_CHECK / --no-version-check, and for an API that publishes no CLI (a local stack).""" try: if _env("NO_VERSION_CHECK") or getattr(args, "no_version_check", False) or _VCHECK["command"] == "cmd_update": return published = _published_version_cached(args.url) if _is_outdated(published): site = cli_site(args.url) # `lhbox update` installs from our own site unless another is named (review 2026-10-08, L5): a deployment's # own site is named in the command the line suggests, never taken from LHBOX_URL behind the person's back how = _update_command(args.url) alt = "" if _pip_upgrade_command() else ", or curl -fsSL %s/install.sh | sh" % site print("lhbox %s is out of date (%s is published): run `%s`%s " "(silence: LHBOX_NO_VERSION_CHECK=1)" % (__version__, published, how, alt), file=sys.stderr) except Exception: # noqa: BLE001 - a courtesy line never breaks a command pass def update_site(value): """The site `lhbox update` may download and run an install script from, normalised (scheme://host[:port][/path], no trailing slash), or None: https, or plain http only on this machine (localhost, 127.0.0.1, ::1: a local stack's site); never credentials, a query or a fragment in it.""" try: parts = urllib.parse.urlsplit((value or "").strip()) parts.port # a malformed port raises here except ValueError: return None host = parts.hostname or "" if (not host or parts.username is not None or parts.password is not None or parts.query or parts.fragment or not (parts.scheme == "https" or (parts.scheme == "http" and host in ("localhost", "127.0.0.1", "::1")))): return None return "%s://%s%s" % (parts.scheme, parts.netloc, parts.path.rstrip("/")) # ---------------------------------------------------------------- lhbox bug: the public issue tracker, filled in # Founder, 2026-10-22: users asked where to report bugs. The tracker is github.com/lakehousebox/lakehousebox (issues only). # `lhbox bug` builds the bug form's URL with what a report needs from this machine and sends nothing itself: a person reviews # and submits it. The repository is public, so nothing that identifies the person goes in unasked (no key, no organisation, # no home directory, no custom API host) and the text given on the command line is scrubbed of credential shapes. ISSUES_URL = "https://github.com/lakehousebox/lakehousebox" BUG_TEXT_MAX = 2000 # the variables an agent's harness sets (the ones DuckDB 2.0's CLI reads for its agent mode, duckdb.org/2026/10/09/agent-mode) AGENT_ENV_VARS = ("AI_AGENT", "AGENT", "CLAUDECODE", "CURSOR_AGENT", "GEMINI_CLI", "CODEX_SANDBOX", "CODEX_CI") # a name that holds a credential, anywhere in an identifier: LHBOX_DEMO_DATA_CLIENT_SECRET, AWS_SECRET_ACCESS_KEY, api-key; # a name starts a word (an unanchored [\w-]* made a 40 kB word take 74 s, high review). ops/user_reports.py keeps the same list _BUG_SECRET_WORD = (r"[\w-]*?(?:secret|token|password|passwd|credential|key_id|key-id|client_id|client-id|access_key" r"|api_key|api-key)[\w-]*") _BUG_SECRET_SET = r"((?"), # DuckDB's CREATE SECRET options, either quote: CLIENT_SECRET '…', SECRET "…" (the name alone, CREATE SECRET lhbox, stays) (re.compile(r"(?i)\b(CLIENT_SECRET|SECRET|KEY_ID|CLIENT_ID|TOKEN|SESSION_TOKEN)\s+'[^']*'"), r"\1 ''"), (re.compile(r"(?i)\b(CLIENT_SECRET|SECRET|KEY_ID|CLIENT_ID|TOKEN|SESSION_TOKEN)\s+\"[^\"]*\""), r'\1 ""'), # an assignment or a key in JSON/YAML/a dict, quoted (an escaped quote does not end it) or not: export X_SECRET=…, # "client_secret": "…", 'token': '…', secret: … (re.compile(r"(?i)" + _BUG_SECRET_SET + r"'(?:[^'\\]|\\.)*'"), r"\1''"), (re.compile(r"(?i)" + _BUG_SECRET_SET + r"\"(?:[^\"\\]|\\.)*\""), r'\1""'), (re.compile(r"(?i)" + _BUG_SECRET_SET + r"(?![\s'\"])[^\s,;&}'\"]+"), r"\1"), # a flag's value: --client-secret …, --token=… (the next flag is not a value: --show-secrets --human stays) (re.compile(r"(?i)((?"), (re.compile(r"(?i)(X-Amz-(?:Signature|Credential|Security-Token)=)[^&\s]+"), r"\1"), (re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=\-]{8,}"), "Bearer "), (re.compile(r"\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]*"), ""), ) def scrub_report_text(text): """Text bound for a PUBLIC issue with the credential shapes this CLI and the store print replaced, the home directory shown as ~, and cut to BUG_TEXT_MAX characters.""" if not text: return "" text = text[:BUG_TEXT_MAX * 2] # bounded before the patterns run: a pasted blob costs nothing for rx, repl in BUG_SCRUB: text = rx.sub(repl, text) home = os.path.expanduser("~") if home and home not in ("/", "~"): text = text.replace(home, "~") return text if len(text) <= BUG_TEXT_MAX else text[:BUG_TEXT_MAX] + " [cut]" def bug_environment(args): """{field: value} a bug report needs from this machine: lhbox, the OS, the Python running it, every DuckDB `connect` would find, the API (named only when it is LakehouseBox's own) and the agent harness, if any.""" env = {"lhbox": "%s (build %s)" % (__version__, cli_build()), "os": "%s %s (%s)" % (pyplatform.system(), pyplatform.release(), pyplatform.machine()), "python": pyplatform.python_version()} try: found = duckdb_versions() except Exception: # noqa: BLE001 - a report never fails on this found = [] env["duckdb"] = ", ".join("%s (%s)" % (_dotted(v), _kind(where)) for where, v, _ in found) or "none found" api = (args.url or "").rstrip("/") host = urllib.parse.urlsplit(api).hostname or "" env["api"] = api if host == "lakehousebox.com" or host.endswith(".lakehousebox.com") else "a custom URL (not shown)" agent = [n for n in AGENT_ENV_VARS if os.environ.get(n)] env["agent"] = ", ".join(agent) if agent else "none detected" return env def bug_report_url(title, env, what="", command=""): """The bug form's URL with its fields filled in (GitHub fills an issue form's fields from query parameters named by their ids: .github/ISSUE_TEMPLATE/bug.yml in lakehousebox/lakehousebox).""" q = {"template": "bug.yml", "title": title or "", "environment": "\n".join("%s: %s" % (k, v) for k, v in env.items())} if what: q["what"] = what if command: q["command"] = command return ISSUES_URL + "/issues/new?" + urllib.parse.urlencode(q, quote_via=urllib.parse.quote) def cmd_bug(args): """Report a bug in LakehouseBox: the public tracker's bug form, filled in from this machine; nothing is sent.""" env = bug_environment(args) title = scrub_report_text(args.title or "") what = scrub_report_text(args.what or "") command = scrub_report_text(args.command or "") url = bug_report_url(title, env, what, command) if _want_json(args): print_json({"url": url, "title": title, "environment": env, "tracker": ISSUES_URL, "note": "Nothing was sent. Show this url to the person you work for: the form opens filled in, they add " "what happened and submit it. Never add an API key, a catalog secret or their data; a security " "vulnerability goes to %s/security/advisories/new instead." % ISSUES_URL}) return print("A bug report for %s/issues, filled in from this machine (nothing is sent until you submit the form):" % ISSUES_URL) for k, v in env.items(): print(" %-7s %s" % (k, v)) print() print(url) print("\nAdd what you ran, what happened (an error's `code` most of all) and `lhbox doctor`'s output. The tracker is " "public: no keys, no secrets. A security vulnerability: %s/security/advisories/new." % ISSUES_URL, file=sys.stderr) if not args.no_open: _open_browser(url) def cmd_update(args): """Install the published lhbox with the site's own install script (what `curl ... | sh` runs), or say what is out. The site is this CLI's own (SITE_URL), whatever LHBOX_URL or --url name, unless --site names another (security review 2026-10-08, L5: the script runs on this machine); no redirect is followed.""" named = getattr(args, "site", None) site = update_site(named) if named else SITE_URL if not site: die("--site %s: an update is downloaded and run only from an https site (or http on this machine: localhost, " "127.0.0.1, ::1), with no user, query or fragment in the address." % named, EXIT_USAGE) st, body, _ = _http("GET", site + "/cli/lhbox.version", timeout=10, redirects=False) published = body.decode(errors="replace").strip() if st == 200 else "" if not _parse_version(published): die_json("version_unreadable", "could not read %s/cli/lhbox.version" % site, EXIT_SERVER, remedy="try again; or run: curl -fsSL %s/install.sh | sh" % site) behind = _is_outdated(published) result = {"version": __version__, "published_version": published, "up_to_date": not behind} if not behind or args.check: emit(args, result) return pip = _pip_upgrade_command() if pip: die_json("installed_by_pip", "this lhbox was installed with pip or pipx; the installer would put a second copy " "in ~/.local/bin", EXIT_USAGE, remedy="run: %s" % pip) st, script, _ = _http("GET", site + "/install.sh", timeout=30, redirects=False) if st != 200 or not script.strip(): die_json("install_script_unreadable", "could not read %s/install.sh" % site, EXIT_SERVER, remedy="try again; or run: curl -fsSL %s/install.sh | sh" % site) print("updating lhbox %s -> %s with %s/install.sh" % (__version__, published, site), file=sys.stderr) rc = subprocess.run(["sh"], input=script, stdout=sys.stderr).returncode if rc != 0: die_json("update_failed", "the install script exited %d" % rc, EXIT_ERROR, remedy="run it yourself to see why: curl -fsSL %s/install.sh | sh" % site) try: os.remove(VERSION_CHECK_FILE) except OSError: pass emit(args, dict(result, updated=True)) def _logout_org(args, entry): """The organisation of a device-login connection: --org, else the one saved with it (no request), else the caller's only one. None when the key is no longer accepted (401): nothing live to revoke.""" org = getattr(args, "org", None) or (entry.get("connection") or {}).get("org_id") if org: return org status, body = request_status(args, "GET", "/v1/orgs") if status == 401: return None if status >= 400: _fail("GET", "/v1/orgs", status, body) orgs = (body or {}).get("organizations") or [] if len(orgs) == 1: return orgs[0]["org_id"] die("You belong to %d organisations; pass --org (lhbox org list)." % len(orgs), EXIT_USAGE) def _logout_revoke(args, entry): """Revoke what the saved login holds -> True (revoked), False (the API no longer knows the key: only forget it). Any other failure exits through _fail and the login stays saved. A device-login connection (`token_id`) is revoked whole, with its own key (#2085); an API that refuses a token revoking itself (403, before #2085) gets the key alone revoked instead. The key's id is the saved one, else read from the key (a login saved without it, #2492), and every revoke is sent WITH the saved key, never --api-key or LHBOX_API_KEY: another key would be refused (404) and the saved one forgotten while still live.""" paths = [] if entry.get("token_id"): org = _logout_org(args, entry) if org is None: return False paths.append("/v1/orgs/%s/tokens/%s" % (urllib.parse.quote(org), urllib.parse.quote(entry["token_id"]))) key_id = entry.get("key_id") or _key_id_of(entry.get("api_key")) # a login saved without key_id too (#2492) if key_id: paths.append("/v1/api-keys/%s" % urllib.parse.quote(key_id, safe="")) if not paths: return None for i, path in enumerate(paths): status, body = request_status(args, "DELETE", path, bearer=entry.get("api_key") or None) if status in (401, 404): return False # refused or gone already: nothing live to revoke if status == 403 and i + 1 < len(paths): continue if status >= 400: _fail("DELETE", path, status, body) return True return None def cmd_logout(args): """Revoke the key this machine's login holds and forget it. A key the API no longer knows (revoked elsewhere) is only forgotten; any other failure keeps the local login, so nothing is left live and unreachable.""" url = args.url.rstrip("/") _read_file(strict=True) # an unreadable file is not "no saved login" (#2573) creds = saved_credentials() entry = creds.get(url) or {} if entry.get("kind") == "client_credentials" and not entry.get("api_key"): # a service account's login holds no key of ours: nothing to revoke here (the application is disabled in the # directory, or the service account deleted by an admin); the saved settings are forgotten (review of #1450, 5) with _cred_lock(): raw = _read_file(strict=True) profiles = _profiles_of(raw) profiles.get(active_profile(), {}).pop(url, None) _write_file(_raw_of(profiles, raw.get("active"))) _DIRECTORY_TOKEN.clear() emit(args, {"logged_out": True, "url": url, "key_revoked": None, "kind": "client_credentials", "removed_from": CRED_FILE_SHOWN, "note": "The service account's settings are forgotten (no secret or token was saved). It is still " "registered: an admin deletes it with lhbox org service-account delete."}) return if not entry.get("api_key"): emit(args, {"logged_out": False, "url": url, "note": "no saved login for %s in %s" % (url, CRED_FILE_SHOWN)}) return revoked = None if not args.local: revoked = _logout_revoke(args, entry) with _cred_lock(): raw = _read_file(strict=True) profiles = _profiles_of(raw) mine = profiles.get(active_profile(), {}) if (mine.get(url) or {}).get("api_key") == entry.get("api_key"): # not a login saved meanwhile (#2642) mine.pop(url, None) _write_file(_raw_of(profiles, raw.get("active"))) emit(args, {"logged_out": True, "url": url, "key_revoked": revoked, "removed_from": CRED_FILE_SHOWN}) def _profile_rows(): raw = _read_file() profiles = _profiles_of(raw) active = active_profile(False) return [{"profile": n, "active": n == active, "apis": sorted(m)} for n, m in sorted(profiles.items()) if m or n == active] def cmd_profile_list(args): emit(args, _profile_rows(), ["profile", "active", "apis"]) def cmd_profile_use(args): with _cred_lock(): profiles = _profiles_of(_read_file(strict=True)) if args.name != DEFAULT_PROFILE and (not PROFILE_RE.match(args.name) or not profiles.get(args.name)): die_json("profile_not_found", "no saved login under the profile %r" % args.name, EXIT_NOTFOUND, remedy="profiles on this machine: %s; make one with `lhbox --profile %s login`" % (", ".join(n for n, m in sorted(profiles.items()) if m) or "none", args.name)) _write_file(_raw_of(profiles, args.name)) emit(args, {"active": args.name}) def cmd_profile_delete(args): raw = _read_file(strict=True) profiles = _profiles_of(raw) if not profiles.get(args.name): die_json("profile_not_found", "no saved login under the profile %r" % args.name, EXIT_NOTFOUND, remedy="`lhbox profile list` shows them") _confirm_irreversible(args, "Delete the saved login of profile %s from this machine (its key stays valid at the API: " "`lhbox logout --profile %s` revokes it first)" % (args.name, args.name)) with _cred_lock(): # read again under the lock: the confirmation above may have waited on a person raw = _read_file(strict=True) profiles = _profiles_of(raw) profiles[args.name] = {} active = raw.get("active") _write_file(_raw_of(profiles, None if active == args.name else active)) emit(args, {"deleted": args.name}) ENV_CHECK_NAMES = ("LHBOX_API_KEY", "LHBOX_URL", "LHBOX_CREDENTIALS", "LHBOX_PROFILE", "LHBOX_NO_VERSION_CHECK") def cmd_env_check(args): """`set` or `missing` for each LHBOX_* variable and the saved login; never a value (a model that echoes its environment cannot leak a key through this command).""" rows = [{"name": n, "status": "set" if os.environ.get(n) else "missing"} for n in ENV_CHECK_NAMES] saved = bool((saved_credentials().get(args.url.rstrip("/")) or {}).get("api_key")) rows.append({"name": "saved login (%s)" % CRED_FILE_SHOWN, "status": "set" if saved else "missing"}) emit(args, rows, ["name", "status"]) def cli_site(api_url): """The website that publishes the CLI for an API: https://api. -> https://; None for any other shape (a local stack publishes no CLI), like mcp_remote_url.""" parts = urllib.parse.urlsplit(api_url.rstrip("/")) if parts.scheme == "https" and (parts.hostname or "").startswith("api.") and parts.path in ("", "/"): return "https://" + parts.hostname[4:] return None def cli_published_check(api_url): """(status, detail, extra) for doctor's `cli` line: this lhbox against the one the site publishes (cli/lhbox.sha256 and cli/lhbox.version, two small files). Never a FAIL: an older CLI still works, so it is a WARN; no site, or the site unreachable, is a quiet SKIP.""" site = cli_site(api_url) mine = "lhbox %s (build %s)" % (__version__, cli_build()) if not site: return "SKIP", "%s; %s publishes no CLI to compare with" % (mine, api_url.rstrip("/")), {"version": __version__} st, body, _ = _http("GET", site + "/cli/lhbox.sha256", timeout=5) published_sha = body.decode(errors="replace").split()[0].lower() if st == 200 and body.split() else "" if not re.fullmatch(r"[0-9a-f]{64}", published_sha): return "SKIP", "%s; could not read %s/cli/lhbox.sha256 to compare" % (mine, site), {"version": __version__} extra = {"version": __version__, "build": cli_build(), "published_build": published_sha[:12]} if published_sha == _self_sha256(): return "PASS", "%s, the build %s publishes" % (mine, site), extra st, body, _ = _http("GET", site + "/cli/lhbox.version", timeout=5) published = body.decode(errors="replace").strip() if st == 200 else "" theirs = _parse_version(published) if theirs: extra["published_version"] = "%d.%d.%d" % theirs upgrade = "update with: %s" % (_pip_upgrade_command() or "curl -fsSL %s/install.sh | sh" % site) if theirs and theirs < (_parse_version(__version__) or (0, 0, 0)): return "PASS", "%s, newer than the %s published at %s (a development copy)" % (mine, extra["published_version"], site), extra if theirs and theirs > (_parse_version(__version__) or (0, 0, 0)): return "WARN", "%s; a newer lhbox %s is published; %s" % (mine, extra["published_version"], upgrade), extra return "WARN", "%s; %s publishes a different build (%s); %s" % (mine, site, published_sha[:12], upgrade), extra def _doctor_default(args, rows): """Which of several visible catalogs `doctor` checks without --catalog -> (row, why): the one the saved login names (its warehouse_id), else the oldest one the caller holds a level on -- the rule /v1/onboard uses for a login's default catalog. Never None for a non-empty list (feedback 2026-11-02, twice: with 13 catalogs visible every check after `catalog` was skipped, and a key given as LHBOX_API_KEY has no saved login to name one). Only doctor picks one: `duckdb`, `connect` and the rest have no default among several (resolve_catalog), so doctor names the flag they need (#2508).""" wid = (_saved_connection(args) or {}).get("warehouse_id") hit = next((w for w in rows if wid and _cid(w) == wid), None) if hit: return hit, "the one this login saved" held = [w for w in rows if w.get("my_level") not in (None, "none")] or rows return min(held, key=lambda w: w.get("created_at") or ""), "your oldest" def cmd_doctor(args): """Every step between this machine and a working DuckDB session, checked in order and reported one line each (PASS / FAIL / SKIP; `--json` for the same as an object): the API, the credential, the catalog (--catalog, else the only one; with several, the one this login saved or the oldest held, and the other commands then need --catalog naming it: they have no default among several, #2508), the recipe and its level, a READ through the catalog's REST API with the recipe's credential, a write-POLICY probe that mutates nothing (two signed S3 requests: HEAD on the bucket and ListObjectsV2 with max-keys=1, which the bucket policy accepts only for the identity the recipe carries -- it says the identity is accepted, NOT that a write would succeed: it printed PASS through the 500 window of 2026-09-20), the optional real write probe (--write-probe: PUT + DELETE of a 0-byte .parquet as the recipe's identity, the store's error quoted verbatim), the DuckDB on this machine, and last this lhbox against the one the site publishes (WARN when a newer one is out). Without --write-probe nothing is created, written or deleted. A catalog whose row says status: provisioning FAILS the catalog line with the reason. Exit 0 when every line is PASS, SKIP or WARN, 1 otherwise.""" checks = [] picked = [] # the catalog doctor chose among several: the other commands need --catalog def add(check, status, detail, **extra): checks.append({"check": check, "status": status, "detail": detail, **extra}) return status == "PASS" def finish(): # last, and on every path: which lhbox this is, and whether the site publishes a newer one (WARN is not a failure) shadow = _shadowing_lhbox_package() if shadow: add("cli-package", "WARN", "%s is the PyPI placeholder `lhbox`, not this CLI (the package is `lakehousebox`): " "it shadows lhbox.py on import. Remedy: pip uninstall lhbox (the CLI stays: pip install -U lakehousebox)." % shadow, path=shadow, remedy="pip uninstall lhbox") st, detail, extra = cli_published_check(args.url) add("cli", st, detail, **extra) ok = all(c["status"] in ("PASS", "SKIP", "WARN") for c in checks) if _want_json(args): print_json({"ok": ok, "url": args.url.rstrip("/"), "checks": checks}) else: for c in checks: print("%-4s %-11s %s" % (c["status"], c["check"], c["detail"])) print() print(("Everything a DuckDB session needs is in place%s." % ( ": lhbox duckdb --catalog %s" % picked[0] if picked else "")) if ok else "Not ready: the FAIL lines say what to fix.") sys.exit(EXIT_OK if ok else EXIT_ERROR) def skip_rest(*names): for n in names: add(n, "SKIP", "not checked: an earlier check failed") # 1. the API base = args.url.rstrip("/") st, body, _ = _http("GET", base + "/healthz", timeout=20) try: health = json.loads(body) if st == 200 else {} except ValueError: health = {} if st == 200 and health.get("ok"): add("api", "PASS", "%s reachable%s; catalog_ok %s; issuer %s" % ( base, " (version %s)" % health["version"] if health.get("version") else "", health.get("catalog_ok"), health.get("issuer")), **{k: health.get(k) for k in ("version", "catalog_ok", "issuer") if k in health}) else: add("api", "FAIL", "%s/healthz -> %s" % (base, "unreachable: " + body.decode(errors="replace") if st == 0 else "HTTP %d %s" % (st, body.decode(errors="replace")[:120].strip()))) skip_rest("credential", "catalog", "recipe", "read", "write-policy", "write-probe", "duckdb") finish() # 2. the credential st, me = request_status(args, "GET", "/v1/usage?days=1", timeout=30) # no history read here (#3517) if st != 200: err = (me.get("error") or {}) if isinstance(me, dict) else {} add("credential", "FAIL", "GET /v1/usage -> HTTP %d %s: %s%s" % (st, err.get("code", ""), err.get("message", ""), " Remedy: " + err["remedy"] if err.get("remedy") else "")) skip_rest("catalog", "recipe", "read", "write-policy", "write-probe", "duckdb") finish() st_o, orgs = request_status(args, "GET", "/v1/orgs", timeout=30) org_rows = (orgs.get("organizations") or []) if st_o == 200 and isinstance(orgs, dict) else [] org_text = ", ".join("%s (%s)" % (o.get("name") or o.get("org_id"), o.get("role") or "-") for o in org_rows) or "no organisation" add("credential", "PASS", "%s %r; organisation %s" % (me.get("kind"), me.get("display_name"), org_text), kind=me.get("kind"), display_name=me.get("display_name"), organizations=org_rows) # 3. the catalog: the one --catalog names, else the only one, else doctor's pick (_doctor_default) rows = _all_warehouses(args, me.get("projects")) want = getattr(args, "warehouse", None) if want: hits = [w for w in rows if want in (_cid(w), w.get("name"))] if len(hits) != 1: add("catalog", "FAIL", "%d of the %d catalogs you can see match %r: %s" % ( len(hits), len(rows), want, ", ".join("%s (%s)" % (w.get("name"), _cid(w)) for w in rows) or "none")) skip_rest("recipe", "read", "write-policy", "write-probe") cat = None else: cat = hits[0] elif len(_own_catalogs(rows)) == 1: cat = _own_catalogs(rows)[0] elif rows: # several visible: the default one (_doctor_default), so the checks after this one still run cat, why_this = _doctor_default(args, _own_catalogs(rows)) picked.append(cat.get("name") or _cid(cat)) else: cat = None add("catalog", "FAIL", "no catalog is visible; create one with: lhbox catalog create ") skip_rest("recipe", "read", "write-policy", "write-probe") if cat and cat.get("status") == "provisioning": # the row itself says the store has not accepted a write yet (the control plane's own probe at creation was # refused, STATE.md 2026-09-21); the recipe would answer 503 and an engine would meet the same refusal add("catalog", "FAIL", "%s (%s) is still provisioning: its storage refused the first write when it was created, and the " "control plane is retrying every 30 s for 10 min. Wait 30 s and run lhbox doctor again; " "lhbox catalog get %s shows status." % (cat.get("name"), _cid(cat), cat.get("name")), name=cat.get("name"), warehouse_id=_cid(cat), catalog_status="provisioning", retry_after_seconds=30) skip_rest("recipe", "read", "write-policy", "write-probe") cat = None if cat: # the catalog's default format version is worth a word only when it is not the default 3 (a catalog from before # 2026-11-15, or set back to 2): its new tables cannot hold geometry fv_note = ("; new tables LakehouseBox creates here are format version %s (no geometry columns: GET /v1/config/formats)" % cat["default_format_version"]) if cat.get("default_format_version") not in (None, 3) else "" add("catalog", "PASS", "%s (%s), your level %s%s%s%s" % (cat.get("name"), _cid(cat), cat.get("my_level") or "none", " via " + cat["my_via"] if cat.get("my_via") else "", "" if want else ("; the only one, so it is the default" if len(rows) == 1 else "; checked as %s, of %d: lhbox duckdb, connect and the rest have " "no default among several and need --catalog %s" % (why_this, len(rows), cat.get("name") or _cid(cat))), fv_note), name=cat.get("name"), warehouse_id=_cid(cat), my_level=cat.get("my_level"), **({"default_format_version": cat["default_format_version"]} if cat.get("default_format_version") is not None else {})) # 4. the recipe st, rec = request_status(args, "GET", "/v1/connection?" + urllib.parse.urlencode({"catalog_id": _cid(cat), "engine": "duckdb"}), timeout=90) if st != 200: err = (rec.get("error") or {}) if isinstance(rec, dict) else {} add("recipe", "FAIL", "GET /v1/connection -> HTTP %d %s: %s%s" % (st, err.get("code", ""), err.get("message", ""), " Remedy: " + err["remedy"] if err.get("remedy") else "")) skip_rest("read", "write-policy", "write-probe") elif isinstance(rec, dict) and rec.get("credentials") == "vended_only": # a service account or an application connection: no key pair to probe the storage with (review of #1450, 4) add("recipe", "PASS", "vended-only at level %s: no static catalog key for this identity. %s" % (rec.get("level"), VENDED_ONLY_REMEDY), level=rec.get("level"), credentials="vended_only") for n in ("read", "write-policy", "write-probe"): add(n, "SKIP", "not checked: this identity has no static catalog key to check with") else: level = rec.get("level") cred = rec.get("catalog_credential") or {} add("recipe", "PASS", "duckdb recipe vended at level %s%s; identity %s; catalog %s; storage %s" % ( level, " via " + rec["level_via"] if rec.get("level_via") else "", rec.get("identity"), rec.get("catalog_uri"), rec.get("storage_endpoint")), level=level, level_via=rec.get("level_via"), identity=rec.get("identity"), catalog_uri=rec.get("catalog_uri"), storage_endpoint=rec.get("storage_endpoint"), bucket=rec.get("warehouse_name")) # 5. read: the catalog's REST API with the recipe's credential ok, detail, _ns = catalog_read_probe(rec.get("catalog_uri") or "", rec.get("warehouse") or "", cred.get("client_id") or "", cred.get("client_secret") or "", rec.get("warehouse_name") or "") add("read", "PASS" if ok else "FAIL", detail) # 6. write-policy: the storage accepts the identity; nothing is written. The recipe's catalog_credential IS # the identity's S3 key pair (the DuckDB recipe uses it as KEY_ID/SECRET), so no vending call is needed. # This line cannot see a store that refuses writes (it passed through the 500 window): that is write-probe. s_ok, s_detail = s3_bucket_probe(rec.get("storage_endpoint") or "", rec.get("warehouse_name") or "", cred.get("client_id") or "", cred.get("client_secret") or "") if level == "write": add("write-policy", "PASS" if s_ok else "FAIL", "credential vended at write; bucket accepts the identity (no object written): " + s_detail if s_ok else s_detail) # 7. write-probe: opt-in, the real thing -- a 0-byte .parquet written and deleted as the identity if not getattr(args, "write_probe", False): add("write-probe", "SKIP", "not run; --write-probe writes and deletes a 0-byte %s in %s as the recipe's identity " "(the only check that sees a store refusing writes)" % (WRITE_PROBE_KEY, rec.get("warehouse_name"))) elif not s_ok: add("write-probe", "SKIP", "not run: the bucket refused the identity") else: w_ok, w_detail = s3_write_probe(rec.get("storage_endpoint") or "", rec.get("warehouse_name") or "", cred.get("client_id") or "", cred.get("client_secret") or "") add("write-probe", "PASS" if w_ok else "FAIL", w_detail, key=WRITE_PROBE_KEY, bucket=rec.get("warehouse_name")) else: add("storage", "PASS" if s_ok else "FAIL", "read-only identity; " + s_detail) add("write-policy", "SKIP", "your level on this catalog is %s: this credential cannot write; a write holder can grant write " "(lhbox catalog grant --catalog %s --principal --level write)" % (level, cat.get("name"))) add("write-probe", "SKIP", "not run: a read credential cannot write") # 8. the DuckDB on this machine: the interpreter running this CLI first, then python3 on PATH, then the binary found = duckdb_versions() if not found: add("duckdb", "SKIP", "no DuckDB: not in %s (the python running lhbox), not in python3 on PATH, no `duckdb` binary; " "install one (%s -m pip install 'duckdb>=%s' for `lhbox table import` and `lhbox duckdb --persist`; the " "interactive `lhbox duckdb` shell runs the duckdb binary: https://duckdb.org/install)" % (_agent_python(), _agent_python(), _dotted(DUCKDB_MIN))) else: old = [f for f in found if f[1] < DUCKDB_MIN] good = [f for f in found if f[1] >= DUCKDB_MIN] versions = [{"where": w, "version": _dotted(v), "ok": v >= DUCKDB_MIN, "via": _via(w), "kind": _kind(w)} for w, v, _ in found] say = lambda fs: ", ".join(_say_version(where, v) for where, v, _ in fs) # noqa: E731 if not good: add("duckdb", "FAIL", say(old) + ": below %s, which writes manifest lists the catalog's maintenance cannot read; " "upgrade before writing: %s" % (_dotted(DUCKDB_MIN), "; ".join(_upgrade_hint(w) for w, _, _ in old)), versions=versions) elif old: # nothing to fix, something to choose: the agent must run the recipe in the new one add("duckdb", "PASS", "use %s; NOT %s, below %s (it writes manifest lists the catalog's maintenance cannot read; %s)" % (say(good), say(old), _dotted(DUCKDB_MIN), "; ".join(_upgrade_hint(w) for w, _, _ in old)), versions=versions) else: add("duckdb", "PASS", say(good) + "; %s or newer, writes are maintained" % _dotted(DUCKDB_MIN), versions=versions) finish() QUERY_MAX_ROWS, QUERY_MAX_CHARS = 2000, 50_000 # the query service's caps (query/service.py MAX_CHARS) def _query_catalog(sql, out): """The one catalog a query read, when the answer says so: the tables in `snapshots` (catalog.namespace.table) whose catalog the SQL names directly -- a public catalog read through its alias (commons_pubdata.…, "commons/pubdata".…) is shown under its own name, which `lhbox duckdb --catalog` would not find. None when it is not exactly one.""" seen = set() for snap in out.get("snapshots") or []: name = str((snap or {}).get("table") or "").split(".", 1)[0] if name and re.search(r'(?") hint = {"why": "lhbox query is a quick look on the shared server engine: 20 seconds, at most %s rows and about %s " "characters per answer. This answer was cut by %s, so it is not the whole result." % ("{:,}".format(QUERY_MAX_ROWS), "{:,}".format(QUERY_MAX_CHARS), cap), "options": ["Aggregate or filter in SQL so the answer fits." + ( " A row cut: --max-rows up to %d." % QUERY_MAX_ROWS if by == "rows" else ""), "Run the same SQL in your own DuckDB, with no row or character cap: `%s`." % command], "command": command} if not catalog: hint["command_note"] = " is the catalog the SQL reads (lhbox catalog list); a public one is /." return hint def cmd_query(args): """POST /v1/query: one read statement run in DuckDB on the server over the catalogs you can read (research/33). Piped or --json: the answer as it comes, plus `local_compute` when it was cut (#1800). On a terminal: the rows as a table, then what was cut and how long it took. --require-complete: a cut answer exits 2 after printing it. For anything heavier than a quick look, `lhbox duckdb` runs your own DuckDB (no time limit, your compute).""" sql = args.sql if sql == "-": sql = sys.stdin.read() if not sql or not sql.strip(): die("Give the SQL as the argument, or '-' to read it from stdin.", EXIT_USAGE) body = {"sql": sql} if args.max_rows is not None: body["max_rows"] = args.max_rows if getattr(args, "dry_run", False): body["dry_run"] = True if getattr(args, "engine", None): body["engine"] = args.engine out = request(args, "POST", "/v1/query", body) cut = bool(out.get("truncated")) and not out.get("dry_run") if cut: out = dict(out, local_compute=_query_local_compute(sql, out)) if _want_json(args): print_json(out) _require_complete(args, out, cut) return if out.get("dry_run"): # what it would read, from the tables' metadata; nothing ran def figure(v, fmt=str): return "?" if v is None else fmt(v) for t in out.get("tables") or []: if t.get("unknown"): print("%s: %s" % (t.get("table"), t["unknown"])) else: print("%s: %s rows, %s files, %s (snapshot %s)" % (t.get("table"), figure(t.get("rows"), "{:,}".format), figure(t.get("data_files")), figure(t.get("bytes"), fmt_bytes), t.get("snapshot_id") or "none: empty")) most = out.get("reads_at_most") if most: print("reads at most %s rows in %s files, %s; filters on partitions and file statistics usually read less" % (figure(most.get("rows"), "{:,}".format), figure(most.get("data_files")), figure(most.get("bytes"), fmt_bytes))) if out.get("tables_note"): print(out["tables_note"]) print("a repeat would be answered from the cache" if out.get("cached") else "not cached: it would run") return # rows keyed by POSITION, the names only as headers: two columns called `id` (a join) must both print (review of #356) names = [c.get("name") for c in out.get("columns") or []] keys = ["c%d" % i for i in range(len(names))] rows = [dict(zip(keys, [json.dumps(v) if isinstance(v, (dict, list)) else v for v in r])) for r in out.get("rows") or []] if rows: _table(rows, keys, dict(zip(keys, names))) else: print("(no rows)") note = "%d row%s" % (out.get("row_count", 0), "" if out.get("row_count") == 1 else "s") if cut: note += ", cut by the %s cap: NOT the whole result" % (out.get("truncated_by") or "size") note += " · %s ms" % out.get("elapsed_ms", "?") if out.get("queued_ms"): note += " (+%s ms queued)" % out["queued_ms"] print(note) if cut: for line in out["local_compute"]["options"]: print(" - " + line) _require_complete(args, out, cut) def _require_complete(args, out, cut): """--require-complete: the answer is printed as always, then a cut one is a refusal (exit 2, the envelope on stderr) so a script need not read `truncated` itself. Without the flag a cut answer exits 0, as it always has.""" if not (cut and getattr(args, "require_complete", False)): return sys.stdout.flush() msg = ("The answer was cut by the %s cap (%d rows returned): it is not the whole result." % (out.get("truncated_by") or "size", out.get("row_count") or 0)) if not _want_json(args): print(msg + " (--require-complete)", file=sys.stderr) sys.exit(EXIT_LIMIT) die_json("incomplete_result", msg, EXIT_LIMIT, truncated_by=out.get("truncated_by"), remedy=" ".join(out["local_compute"]["options"]), command=out["local_compute"]["command"]) def cmd_usage(args): """Every limit and its headroom; with --catalog, one catalog's storage and traffic, day by day. Piped or --json the answer is the brief object (identity, organisations, catalogs with their footprint, limits with headroom and enforced, the next step; the third simulated user, 2026-09-21: the full document is ~600 lines); `--full` is GET /v1/usage as it comes; `--human` the tables, unchanged (the limits table says which are enforced).""" q = {} if getattr(args, "days", None): q["days"] = args.days out = request(args, "GET", "/v1/usage" + ("?" + urllib.parse.urlencode(q) if q else "")) if not getattr(args, "warehouse", None): if _want_json(args): emit(args, out if getattr(args, "full", False) else _usage_brief_json(out)) else: emit_usage_human(args, out) return # the per-catalog view: the row of that catalog (by id or by name, as everywhere), with its project want = args.warehouse hits = [(p, w) for p in out.get("projects", []) for w in p.get("warehouse_storage", []) if want in (_cid(w), w.get("name"))] if not hits: die("No catalog %r among the %d you can see; list them with: lhbox catalog list" % ( want, sum(len(p.get("warehouse_storage", [])) for p in out.get("projects", []))), EXIT_NOTFOUND) if len(hits) > 1 and len({_cid(w) for _, w in hits}) > 1: die("The name %r matches %d catalogs; use the catalog id (warehouse_id): %s" % ( want, len(hits), ", ".join(_cid(w) for _, w in hits)), EXIT_ERROR) proj, w = hits[0] view = {"warehouse_id": _cid(w), "name": w["name"], "project_id": proj["project_id"], "org_id": proj.get("org_id"), "tier": w.get("tier"), "buckets": w.get("buckets"), "latest": {k: w.get(k) for k in ("bytes", "table_bytes", "blob_bytes", "objects", "blob_objects", "complete", "errors", "measured_at", "unmetered")}, "trend": w.get("trend"), "traffic": w.get("traffic"), "traffic_note": w.get("traffic_note"), "history_days": out.get("history_days"), "history": w.get("history", [])} if args.json or (not args.human and not sys.stdout.isatty()): emit(args, view) return print("catalog %s (%s)" % (w["name"], _cid(w))) print("buckets tables %s blobs %s" % (view["buckets"]["table"], view["buckets"]["blob"]) if view["buckets"] else "") lat = view["latest"] if lat["unmetered"]: print("stored not measured yet (the first sample is pending)") else: print("stored %s in %s objects (tables %s, blobs %s%s) measured %s" % ( fmt_bytes(lat["bytes"]), _all_objects(lat), fmt_bytes(lat["table_bytes"]), fmt_bytes(lat["blob_bytes"]), "" if lat["complete"] else "; INCOMPLETE: an undercount", lat["measured_at"])) for line in _sample_error_lines(lat.get("errors"), lat["complete"]): print(line) if view["trend"]: t = view["trend"] print("trend %s%s over %d days (%d measured), %+d objects" % ( "+" if t["bytes_delta"] >= 0 else "-", fmt_bytes(abs(t["bytes_delta"])), t["days"], t["days_measured"], t["objects_delta"])) if view["traffic"]: t = view["traffic"] print("traffic %s S3 requests (%s failed), %s in, %s out over %d days%s" % ( t["requests"], t["requests_failed"], fmt_bytes(t["bytes_in"]), fmt_bytes(t["bytes_out"]), t["days"], "; %d counter reset(s)" % t["resets"] if t.get("resets") else "")) elif view["traffic_note"]: print("traffic none counted yet: " + view["traffic_note"]) print() rows = [{"day": r["day"], "stored": fmt_bytes(r["bytes"]) if r["bytes"] is not None else "-", "objects": _all_objects(r) if r["objects"] is not None else "-", "samples": r["samples"], "requests": r["requests"] if r["requests"] is not None else "-", "failed": r["requests_failed"] if r["requests_failed"] is not None else "-", "bytes_in": fmt_bytes(r["bytes_in"]) if r["bytes_in"] is not None else "-", "bytes_out": fmt_bytes(r["bytes_out"]) if r["bytes_out"] is not None else "-"} for r in view["history"]] emit(args, rows, ["day", "stored", "objects", "samples", "requests", "failed", "bytes_in", "bytes_out"]) def _all_objects(d): """Table objects + uploaded files: the count that goes with `bytes`, which sums both (#2365); None when unmeasured.""" return None if d.get("objects") is None else d["objects"] + (d.get("blob_objects") or 0) def _sample_error_lines(errors, complete=True): """The cause of an incomplete sample, one line per entry (`errors` is the API's {what: message}; None when nothing went wrong). A sample flagged incomplete without a recorded cause says so (rows from before 2026-09-21).""" if errors: return [" error %s: %s" % (k, v) for k, v in sorted(errors.items())] if complete is False: return [" error the cause was not recorded (a sample from before errors were kept; the host's sweep log has it)"] return [] def _usage_brief_json(out): """The brief object of `lhbox usage`: identity, organisations with their two tiers, one row per catalog with its latest footprint, limits with headroom and enforced, the next step. `--full` is the whole document.""" projects = out.get("projects") or [] catalogs = [{"catalog": w.get("name"), "warehouse_id": _cid(w), "project": p.get("name"), "tier": w.get("tier"), "bytes": w.get("bytes"), "objects": w.get("objects"), "measured_at": w.get("measured_at"), "unmetered": w.get("unmetered"), **({"measuring": True} if w.get("measuring") else {})} for p in projects for w in p.get("warehouse_storage") or []] orgs = [{"org_id": o.get("org_id"), "role": o.get("role"), **{tier: {k: (o.get(tier) or {}).get(k) for k in ("current", "limit", "headroom", "unmetered")} for tier in ("storage_bytes", "public_storage_bytes") if o.get(tier)}} for o in out.get("organizations") or []] if catalogs: nxt = ("lhbox usage --catalog (one catalog's storage and traffic by day); " "lhbox catalog measure (measure it now instead of at the next reading, every few minutes)") else: nxt = "lhbox catalog create (a catalog first)" return {"identity": _identity_block(out), "organisations": orgs, "catalogs": catalogs, "limits": _brief_limits(out), "history_days": out.get("history_days"), "next": nxt, "full": "lhbox usage --full"} def fmt_bytes(n): """1234567 -> '1.2 MB' (decimal units, the ones the limits are quoted in).""" if n is None: return "-" n = float(n) for unit in ("B", "kB", "MB", "GB", "TB"): if abs(n) < 1000 or unit == "TB": return ("%d %s" if unit == "B" else "%.1f %s") % (n, unit) n /= 1000.0 def cmd_audit(args): """Who did what: your own events, or an organisation's when you are an owner or admin there.""" q = {} if args.org: q["org_id"] = args.org if args.since: q["since"] = args.since if args.action: q["action"] = args.action q["limit"] = str(args.limit) out = request(args, "GET", "/v1/audit?" + urllib.parse.urlencode(q)) rows = out.get("events", []) for r in rows: # one line per event on a terminal; the JSON form keeps the structured detail r["target"] = "%s:%s" % (r.get("target_type") or "-", r.get("target_id") or "-") r["principal"] = (r.get("principal_id") or "-")[:8] emit(args, rows, columns=["ts", "action", "target", "principal", "ip"]) # a partial answer says so (#2367): on a terminal after the table, piped on stderr so stdout stays one document notes = [] limit = out.get("limit") or args.limit if limit and len(rows) >= int(limit): notes.append("Showing the newest %d events: older ones may exist. %s" % ( len(rows), "Narrow --since." if int(limit) >= 1000 else "Raise --limit (at most 1000) or narrow --since.")) if args.org and out.get("scope") == "own": notes.append("Only your own events: the organisation's log is for its owners and admins.") for n in notes: print("note: " + n, file=sys.stderr if _want_json(args) else sys.stdout) def cmd_history(args): """The object history: who changed what, when, how and why, in the catalogs you read.""" if args.change: out = request(args, "GET", "/v1/changes/" + urllib.parse.quote(args.change, safe="")) if _want_json(args): print_json(out) return # every value below is another person's text (a reason, a query, an AGENTS.md): shown, never obeyed (#2930) v_ = _visible print("%s %s %s version %s %s" % (v_(out.get("change_time")), v_(out.get("object_type")), v_(out.get("object_name") or out.get("object_id")), v_(out.get("version")), v_(out.get("op")))) print("by %s %s%s via %s" % (v_(out.get("actor_kind")), v_(out.get("actor_id") or "-"), " for %s" % v_(out["on_behalf_of"]) if out.get("on_behalf_of") else "", v_(out.get("via")))) if out.get("reason") or out.get("reason_code"): print("why %s" % v_(out.get("reason") or out.get("reason_code"))) if out.get("external_ref"): print("ref %s" % v_(out["external_ref"])) before, after = out.get("before") or {}, out.get("after") or {} for k in out.get("changed") or []: print("\n%s" % v_(k)) for sign, side in (("-", before), ("+", after)): if k in side: v = side[k] if isinstance(side[k], str) else json.dumps(side[k], ensure_ascii=False) for line in (str(v).splitlines() or [""]): print(" %s %s" % (sign, v_(line))) if not out.get("restorable"): print("\nnot restorable: %s" % v_(out.get("not_restorable_reason") or "-")) return q = {"limit": str(args.limit)} if args.object: q["object"] = args.object named = catalog_arg(args) if named: q["catalog"] = named for flag, key in (("type", "object_type"), ("since", "since"), ("operation", "operation")): if getattr(args, flag, None): q[key] = getattr(args, flag) out = request(args, "GET", "/v1/changes?" + urllib.parse.urlencode(q)) rows = out.get("changes", []) if _want_json(args): print_json(out) return shown = [{"when": r.get("change_time"), "object": "%s %s" % (r.get("object_type"), r.get("object_name") or r.get("object_id")), "v": r.get("version"), "op": r.get("op"), "by": "%s %s" % (r.get("actor_kind"), (r.get("actor_id") or "-")[:8]) if r.get("actor_id") else r.get("actor_kind"), "via": r.get("via"), "changed": ", ".join(r.get("changed") or [])[:60], "why": (r.get("reason") or r.get("reason_code") or "")[:60], "change_id": r.get("change_id")} for r in rows] emit(args, shown, columns=["when", "object", "v", "op", "by", "via", "changed", "why", "change_id"], headers={"change_id": "change id"}) if out.get("truncated"): print("note: the newest %d changes; older ones exist. Narrow --since or raise --limit (at most 500)." % len(rows)) elif not rows: print("No change is recorded%s." % (" for %s" % args.object if args.object else "")) def cmd_restore(args): """Put an object back to a version from its history, or undo everything one operation changed.""" if bool(args.change_id) == bool(args.operation): die("Name one: a change (lhbox restore ) or an operation (lhbox restore --operation ).", EXIT_USAGE) if args.operation: to = "after" if args.redo else "before" _restore_confirm(args, "%s every change of operation %s" % ("Put back" if args.redo else "Undo", args.operation)) out = request(args, "POST", "/v1/changes/operations/%s/restore" % urllib.parse.quote(args.operation, safe=""), {"to": to, "allow_empty": bool(args.allow_empty), **({"actor_id": args.by} if args.by else {})}) if _want_json(args): print_json(out) else: for label, key in (("restored", "restored"), ("already as wanted", "unchanged"), ("FAILED", "failed")): for o in out.get(key) or []: print("%-18s %s %s%s" % (label, _visible(o.get("object_type")), _visible(o.get("object_name") or o.get("object_id")), " (%s: %s)" % (_visible(o.get("code")), _visible(o.get("message"))) if key == "failed" else "")) if out.get("not_readable"): print("%d change(s) of this operation are in catalogs you do not read: left as they are." % out["not_readable"]) if out.get("other_callers"): print("%d change(s) carrying this id were made by someone else: left as they are (lhbox history --operation %s " "shows who; --by undoes theirs)." % (out["other_callers"], args.operation)) if out.get("failed"): sys.exit(EXIT_ERROR) return change = request(args, "GET", "/v1/changes/" + urllib.parse.quote(args.change_id, safe="")) # the version THIS object has now, as the change's own answer says it: a catalog's settings and its AGENTS.md share # one id, so a search by id can answer with the other's version current = change.get("current_version") or change.get("version") to = "before" if args.undo else "after" what = _visible("%s %s" % (change.get("object_type"), change.get("object_name") or change.get("object_id"))) _restore_confirm(args, "Put %s back to %s (it is at version %s now)" % ( what, "what it was before version %s" % change.get("version") if args.undo else "version %s" % change.get("version"), current)) out = request(args, "POST", "/v1/changes/%s/restore" % urllib.parse.quote(args.change_id, safe=""), {"expected_version": current, "to": to, "allow_empty": bool(args.allow_empty)}) if _want_json(args): print_json(out) elif out.get("restored"): made = out.get("change") or {} print("Restored %s: now version %s (%s)." % (what, made.get("version"), ", ".join(made.get("changed") or []) or "no key changed")) if out.get("not_restored"): print("Left as it is now (a restore does not set it): %s." % ", ".join(out["not_restored"])) else: print("Nothing to do: %s is already as that version has it." % what) def _restore_confirm(args, what): """--yes goes through; a person at a terminal on both ends is asked, on stderr (_ask: stdout is the answer's); anyone else (a pipe, --json) is refused before anything is sent, with what to pass.""" if args.yes: return if not (sys.stdin.isatty() and sys.stdout.isatty()) or args.json: die_json("confirmation_needed", "%s? Pass --yes to do it." % what, EXIT_USAGE) if _ask("%s? [y/N] " % what).strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was changed.", EXIT_USAGE) PROJECT_HELP = "project_id (UUID) or project name; list both with: lhbox project list" ORG_HELP = "org_id or the organisation's handle (lhbox org list shows both); default: your only organisation" TOKEN_HELP = "the token's id or its name (lhbox token list shows both)" CATALOG_HELP = ("the catalog's warehouse_id (UUID) or its name; list both with: lhbox catalog list") CATALOG_DEFAULT_HELP = "; default: your only catalog (with several, name one)" PUBLIC_CATALOG_HELP = "; or / for another organisation's PUBLIC catalog, attached read-only as _" # the catalog property behind `table create` without --format-version (founder decision 2026-09-20): the API # and GET /v1/config/formats say which engines write each version; the CLI carries no list of its own FORMAT_DEFAULT_HELP = ("the Iceberg format version (2 or 3) LakehouseBox gives tables IT creates in this catalog: table create " "without --format-version and table import; an engine's own CREATE TABLE " "is honoured as sent") def add_catalog_flag(sp, **kw): """`--catalog`, with `--warehouse` as a HIDDEN twin on the same dest (the API's name): a person and the docs say catalog, a script written against the API keeps working. The two are one mutually exclusive group so `required` means "one of them"; `hidden=True` hides `--catalog` as well (the verbs that take the catalog positionally).""" kw.setdefault("dest", "warehouse") kw.setdefault("metavar", "CATALOG") kw.setdefault("help", CATALOG_HELP) hidden = kw.pop("hidden", False) required = kw.pop("required", False) group = sp.add_mutually_exclusive_group(required=required) if hidden: kw["help"] = argparse.SUPPRESS action = group.add_argument("--catalog", **kw) group.add_argument("--warehouse", **dict(kw, help=argparse.SUPPRESS)) return action def add_catalog_positional(sp, default_rule=True, hide_flag=False, hide_positional=False): """`` as an optional positional next to `--catalog` (2026-09-21: `catalog measure ` wanted the flag): `lhbox catalog measure sales` and `lhbox catalog measure --catalog sales` are one command. catalog_arg() reads them together; resolve_catalog() applies the only-catalog default when neither is given. hide_flag: the positional is the documented form, `--catalog` / `--warehouse` stay as silent aliases (every `catalog `). hide_positional: the other way round, for a group named after something else (`sink create`, `index create`: the group's own resource is the positional elsewhere, convention 2); the positional stays accepted for one release.""" sp.add_argument("catalog_arg", nargs="?", metavar="CATALOG", help=argparse.SUPPRESS if hide_positional else "the catalog's name (or its id; lhbox catalog list shows both)" + (CATALOG_DEFAULT_HELP if default_rule else "")) return add_catalog_flag(sp, help=CATALOG_HELP + (CATALOG_DEFAULT_HELP if default_rule else ""), hidden=hide_flag) def add_table_positional(sp, nargs="?", help=None, name_flag="--name", hidden_flags=True): """The ONE table a command acts on, `[catalog.]namespace.table`, positional (docs/proposals/cli-consistency.md §1, convention 1; _table_ref() reads it). The older `--namespace` / `--name` spelling stays accepted, hidden (`credentials` spelled the name `--table`: name_flag keeps that alias with its old meaning).""" sp.add_argument("table_ref", nargs=nargs, metavar="[CATALOG.]NAMESPACE.TABLE", help=help or "the table: catalog.namespace.table, or namespace.table with --catalog") if hidden_flags: sp.add_argument("--namespace", help=argparse.SUPPRESS) sp.add_argument(name_flag, dest="name", help=argparse.SUPPRESS) def add_token_positional(sp): """`` (name or id) as an optional positional with `--token` / `--token-id` as the twin; token_ref() reads them.""" sp.add_argument("token_arg", nargs="?", metavar="TOKEN", help=TOKEN_HELP) sp.add_argument("--org", help=ORG_HELP) sp.add_argument("--token", "--token-id", dest="token_id", metavar="TOKEN", help=TOKEN_HELP + "; the same as the positional") def add_confirm(sp, kind): """`--confirm [NAME]` / `--yes [NAME]` on every destructive or publishing verb, one spelling pair everywhere. kind "name": the API wants the catalog's name typed out (delete, publish); "optional": accepted, nothing more (unpublish); "hidden": accepted so a script can pass it uniformly, not offered.""" help_text = {"name": "the catalog's name, exactly (a bare --yes confirms the NAME given positionally); this cannot be undone", "optional": "accepted for symmetry with publish; not required", "hidden": argparse.SUPPRESS}[kind] return sp.add_argument("--confirm", "--yes", dest="confirm", nargs="?", const=True, metavar="NAME", help=help_text) def add_drop_flags(sp): """`--yes` skips the [y/N] question (no `--confirm` twin: on the catalog verbs it takes the NAME typed out, and a flag that means something else here would be a trap, high review of #683 finding 7); `--force` is what a PUBLIC catalog wants as well, since a drop there breaks readers without an account.""" sp.add_argument("--yes", dest="yes", action="store_true", help="do not ask (required without a terminal or with --json); the drop cannot be undone") sp.add_argument("--force", action="store_true", help="drop it even in a PUBLIC catalog (an admin only), whose public URL then stops serving it") def add_yes(sp, what, takes_name=False): """`--yes` on an irreversible verb that is not a drop (revoke, rotate, delete of a sink or index, lifecycle clear): asked [y/N] on a terminal; without one, or with --json, a missing --yes is a WARNING in this release and will be refused from the next minor version (docs/proposals/cli-consistency.md §1, convention 3). The hidden `--confirm [NAME]` these verbs accepted before stays accepted and counts as --yes. takes_name: the verbs where `--yes` itself took an optional NAME before (it was `--confirm/--yes [NAME]`); it still does, so `token revoke --yes bot` keeps working (token_ref reads the name from it, review of #429).""" text = ("do not ask: %s cannot be undone. Asked on a terminal; without one (or with --json) --yes will be required " "from the next minor version of lhbox (a warning today)" % what) if takes_name: sp.add_argument("--yes", dest="confirm", nargs="?", const=True, metavar="NAME", help=text) else: sp.add_argument("--yes", dest="yes", action="store_true", help=text) sp.add_argument("--confirm", dest="confirm", nargs="?", const=True, metavar="NAME", help=argparse.SUPPRESS) def _confirm_irreversible(args, what): """The guard of the add_yes verbs, before the request: --yes (or the old --confirm) goes through; a person at a terminal on both ends is asked on stderr; anyone else runs the verb as before --yes existed here (scripts keep working for one release), with a warning on stderr unless the output is JSON.""" if getattr(args, "yes", False) or getattr(args, "confirm", None): return if sys.stdin.isatty() and sys.stdout.isatty() and not args.json: if _ask("%s? This cannot be undone. [y/N] " % what).strip().lower() not in ("y", "yes"): die("Not confirmed; nothing was changed.", EXIT_USAGE) return # a JSON caller's stderr carries nothing but an error envelope (docs/proposals/cli-consistency.md §2): no warning # there; the refusal of the next minor version will be that envelope, with the remedy if not _want_json(args): print("warning: %s without --yes; from the next minor version of lhbox this is refused without a terminal. " "Pass --yes." % what, file=sys.stderr) GLOBAL_FLAGS = ("--url", "--api-key", "--profile", "--json", "--human", "--reason", "--ref") def _accept_globals_everywhere(root): """`--json`, `--human`, `--url`, `--api-key` (and `--no-version-check`) are accepted before AND after the subcommand: the docs write `lhbox connect --human` and `signup … --json`, argparse only knew them before (2026-09-21). Every subparser gets hidden twins whose default is SUPPRESS, so an absent flag leaves the root's value alone; the root gets a hidden `--no-version-check` for the same reason in the other direction.""" root.add_argument("--no-version-check", dest="no_version_check", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS) def walk(p, is_root): if not is_root: have = p._option_string_actions if "--url" not in have: p.add_argument("--url", default=argparse.SUPPRESS, help=argparse.SUPPRESS) if "--api-key" not in have: p.add_argument("--api-key", dest="api_key", default=argparse.SUPPRESS, help=argparse.SUPPRESS) if "--profile" not in have: p.add_argument("--profile", default=argparse.SUPPRESS, help=argparse.SUPPRESS) if "--json" not in have: p.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS) if "--human" not in have: p.add_argument("--human", action="store_true", default=argparse.SUPPRESS, help=argparse.SUPPRESS) if "--reason" not in have: p.add_argument("--reason", default=argparse.SUPPRESS, help=argparse.SUPPRESS) if "--ref" not in have: p.add_argument("--ref", default=argparse.SUPPRESS, help=argparse.SUPPRESS) for action in p._actions: if isinstance(action, argparse._SubParsersAction): seen = set() for sub in action.choices.values(): if id(sub) not in seen and isinstance(sub, argparse.ArgumentParser): # a lazy tree's stubs: not parsers seen.add(id(sub)) walk(sub, False) walk(root, True) # ---------------------------------------------------------------- mcp: the MCP server as a host configuration # `lhbox mcp install` writes the mcpServers entry of docs/mcp.md into Claude Code or Claude # Desktop with the key taken from the credentials file, so the key travels file -> file and is never # shown; `lhbox mcp run` starts the server the same way for a host that is configured by hand. MCP_PACKAGE = "lakehousebox-mcp" # console script and package name of platform/mcp (pyproject.toml) MCP_SERVER_NAME = "lhbox" def mcp_default_source(): """What `uvx --from` installs the server from: the checkout's platform/mcp when this file runs from one (the directory next to cli/), else the package name, which resolves once it is on PyPI (until then mcp_source_problem() refuses it and `mcp install` points at the hosted server).""" here = os.path.dirname(os.path.realpath(__file__)) checkout = os.path.normpath(os.path.join(here, "..", "mcp")) if os.path.isfile(os.path.join(checkout, "pyproject.toml")): return checkout return MCP_PACKAGE def mcp_source_abs(source): """A --from that names a local path, made absolute: a host starts the server from its own working directory, so a relative path written into its entry would break (low review of #1107). A URL or a package requirement unchanged; what counts as a path is what mcp_source_problem() checks as one.""" if "://" in source: return source path = os.path.expanduser(source) if os.sep in source or source.startswith((".", "~")) or os.path.exists(path): return os.path.abspath(path) return source PYPI_JSON = "https://pypi.org/pypi/%s/json" _REQUIREMENT = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?\s*((==|>=|<=|~=|!=|<|>)\s*[^\s;]+)?$") def mcp_source_problem(source): """None when `uvx --from SOURCE` can start the server, else why it cannot -- so `mcp install` never writes, and `mcp run` never starts, a server that dies on its first launch (the external test of 2026-09-25: the package is not on PyPI, and the written entry could not start). A directory must hold a pyproject.toml; a bare package name must be on PyPI (checked, one small GET); anything else (a git+ or https URL, a wheel file) is taken as named.""" if "://" in source: return None # a URL (a VCS URL, an https wheel): uvx resolves what was named path = os.path.expanduser(source) if os.sep in source or source.startswith((".", "~")) or os.path.exists(path): if os.path.isdir(path): return None if os.path.isfile(os.path.join(path, "pyproject.toml")) else "%s holds no pyproject.toml" % source if os.path.isfile(path) and path.endswith(".whl"): return None return "%s does not exist" % source m = _REQUIREMENT.match(source) if not m: return None st, _, _ = _http("GET", PYPI_JSON % m.group(1), timeout=10) if st == 200: return None if st == 404: return "the package %s is not published on PyPI yet" % m.group(1) return "PyPI could not be asked whether %s is published (%s)" % (m.group(1), "unreachable" if st == 0 else "HTTP %d" % st) def mcp_server_entry(source, url, key, command="uvx"): """The one mcpServers value both hosts take (docs/mcp.md). The key and the API base travel in the environment, the only place the server reads them from.""" return {"command": command, "args": ["--from", source, MCP_PACKAGE], "env": {"LHBOX_URL": url.rstrip("/"), "LHBOX_API_KEY": key}} def mcp_remote_url(api_url): """The remote MCP server next to an API: https://api. -> https://mcp./mcp; None for any other shape (a local stack serves no remote MCP; --mcp-url names one).""" parts = urllib.parse.urlsplit(api_url.rstrip("/")) if parts.scheme == "https" and (parts.hostname or "").startswith("api.") and parts.path in ("", "/"): return "https://mcp.%s/mcp" % parts.hostname[4:] return None def self_command(): """How another program runs this lhbox later (Claude Code's headersHelper, an MCP entry's command): this script by its absolute path when it is executable (its shebang finds python3, as the person's own `lhbox` does), else this interpreter and the file (the pip form's lhbox.py, Windows).""" me = os.path.abspath(__file__) if os.name != "nt" and os.access(me, os.X_OK): return [me] return [sys.executable, me] def _self_args(args): """The global flags that make a later run of this lhbox find the same key: the API base (credentials are keyed by it) and the profile in force now, pinned so a later `lhbox profile use` does not move an installed entry.""" return ["--url", args.url.rstrip("/"), "--profile", active_profile()] def _shell_line(argv): """argv as one command line for a shell (Claude Code runs headersHelper through one).""" return subprocess.list2cmdline(argv) if os.name == "nt" else " ".join(shlex.quote(a) for a in argv) def mcp_helper_entry(args, mcp_url): """Claude Code's entry for the remote server WITHOUT the key (security review 2026-10-08, M8: the key was on `claude mcp add-json`'s argv): a headersHelper that Claude Code runs when it connects, and again after a 401 (code.claude.com/docs/en/mcp), which prints the Authorization header from LHBOX_API_KEY or the saved login: `lhbox --url U --profile P mcp headers`. A key that changes (`lhbox login` again) needs no reinstall.""" return {"type": "http", "url": mcp_url, "headersHelper": _shell_line(self_command() + _self_args(args) + ["mcp", "headers"])} def mcp_run_entry(args, source): """Claude Code's stdio entry WITHOUT the key: `lhbox … mcp run --from SOURCE`, which puts the key (LHBOX_API_KEY or the saved login) in the server's environment as it starts it (cmd_mcp_run).""" me = self_command() return {"command": me[0], "args": me[1:] + _self_args(args) + ["mcp", "run", "--from", source]} def mask_key(key): """al_live__ -> al_live__********: enough to recognise a key, never to use it.""" parts = key.split("_") if len(parts) >= 4 and all(parts[:3]): return "_".join(parts[:3]) + "_********" return key[:4] + "********" def mcp_masked(obj, key): """The same object with every occurrence of the key masked, for anything that reaches a terminal.""" return json.loads(json.dumps(obj).replace(key, mask_key(key))) def claude_desktop_config_path(): """Claude Desktop's configuration file, per platform (its documented locations).""" if sys.platform == "darwin": return os.path.expanduser("~/Library/Application Support/Claude/claude_desktop_config.json") if sys.platform.startswith("win"): base = os.environ.get("APPDATA") or os.path.expanduser("~\\AppData\\Roaming") return os.path.join(base, "Claude", "claude_desktop_config.json") base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") return os.path.join(base, "Claude", "claude_desktop_config.json") def merge_mcp_server(path, name, entry): """Set mcpServers[name] in a host's JSON config and keep everything else in it. The previous file, when there is one, is copied to .bak- first, owner-read-only from the moment it exists (it holds the keys of every server in the file; shutil.copy2 kept the source's mode, security review 2026-10-08, M8); the new file is written owner-read-only (it carries a key) through a temporary file and one rename, so a crash leaves either the old file or the new one. Returns the backup path, or None.""" try: with open(path) as fh: cfg = json.load(fh) except FileNotFoundError: cfg = {} except ValueError as exc: die_json("config_unparseable", "%s is not valid JSON: %s" % (path, exc), EXIT_ERROR, remedy="Fix or move the file; nothing was changed.") if not isinstance(cfg, dict) or not isinstance(cfg.get("mcpServers", {}), dict): die_json("config_unexpected", "%s does not hold an object with an mcpServers object" % path, EXIT_ERROR, remedy="Fix or move the file; nothing was changed.") backup = None if os.path.exists(path): backup = path + ".bak-" + time.strftime("%Y%m%d%H%M%S") bfd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) os.fchmod(bfd, 0o600) # an existing file of that name keeps its mode through O_CREAT with open(path, "rb") as src, os.fdopen(bfd, "wb") as dst: shutil.copyfileobj(src, dst) st = os.stat(path) os.utime(backup, ns=(st.st_atime_ns, st.st_mtime_ns)) # the times copy2 kept, without its mode cfg.setdefault("mcpServers", {})[name] = entry os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".tmp" fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) os.fchmod(fd, 0o600) with os.fdopen(fd, "w") as fh: json.dump(cfg, fh, indent=2) fh.write("\n") os.replace(tmp, path) return backup def cmd_mcp_install(args): # the hosted server is the product (founder, 2026-09-25): every client gets it unless stdio is asked for. stdio is a # developer option (a checkout's platform/mcp against a local stack); lakehousebox-mcp is not published anywhere. # --from names what to run locally, so it means stdio (review of #368: it was silently ignored for the remote entry) transport = args.transport or ("stdio" if args.source else "http") if transport == "http" and args.source: die("--from names a local server; it goes with --transport stdio, not http.", EXIT_USAGE) if transport == "http" and args.client == "claude-desktop": # Claude Desktop's config file takes only local servers; its remote route is a custom connector added in the app, # signed in with OAuth in the browser. So nothing is written, no key is needed, and the steps are the answer. remote = args.mcp_url or mcp_remote_url(args.url) if not remote: # a local stack has no hosted server: never point at production's (review of #406) die("No remote MCP server is known for %s; pass --mcp-url, or --transport stdio to run the server locally." % args.url, EXIT_USAGE) emit(args, {"client": "claude-desktop", "transport": "http", "url": remote, "written": False, "next": "In Claude Desktop: Settings > Connectors > Add custom connector, URL %s. You approve it in " "the browser and choose the catalogs it may read; nothing is installed." % remote}) return key = api_key(args) # --api-key, LHBOX_API_KEY, or the credentials file desktop = args.client == "claude-desktop" url = args.url.rstrip("/") if not desktop and getattr(args, "api_key", None) \ and (_env("API_KEY") or (saved_credentials().get(url) or {}).get("api_key")) != key: # Claude Code's entry holds no key (M8 below): `lhbox mcp headers` / `mcp run` look for it again each time Claude # Code connects, and a key given only on this command line is in neither place they look die("The Claude Code entry carries no key: when Claude Code connects, `lhbox mcp headers` reads it from " "LHBOX_API_KEY in Claude Code's environment, else from the login saved for %s, and the key given with " "--api-key is in neither. Nothing was written. Save a login (`lhbox login`), or export LHBOX_API_KEY where " "Claude Code runs and leave out --api-key (a key on a command line is visible to other local users in the " "process list)." % url, EXIT_USAGE) if transport == "http": mcp_url = args.mcp_url or mcp_remote_url(args.url) if not mcp_url: die("No remote MCP server is known for %s; pass --mcp-url, or --transport stdio to run the server locally." % args.url, EXIT_USAGE) # never the key itself: `claude mcp add-json` takes the entry on its command line, which every local user can # read in `ps` while it runs (security review 2026-10-08, M8); Claude Code asks lhbox for the header instead entry = mcp_helper_entry(args, mcp_url) shown = mcp_url key_from = ("Claude Code runs `lhbox mcp headers` (the entry's headersHelper) when it connects: LHBOX_API_KEY in " "Claude Code's environment, else the login saved for %s (profile %s)" % (url, active_profile())) else: source = mcp_source_abs(args.source or mcp_default_source()) command = shutil.which("uvx") # the absolute path: hosts start servers with a short PATH problem = mcp_source_problem(source) or (None if command else "uvx is not on PATH (install uv: https://docs.astral.sh/uv/)") if problem: # nothing written: a configuration that cannot start is worse than none remote = args.mcp_url or mcp_remote_url(args.url) or "https://mcp.lakehousebox.com/mcp" if args.client == "claude-desktop": how = ("Add the hosted server instead: in Claude Desktop, Settings > Connectors > Add custom connector, " "URL %s (you approve it in the browser; nothing to install)." % remote) else: how = ("The hosted server needs nothing installed: run `lhbox mcp install` without --transport stdio " "(it adds %s; Claude Code asks lhbox for your key when it connects)." % remote) die("A local MCP server would not start: %s. Nothing was written. %s Or point --from at a checkout's " "platform/mcp directory." % (problem, how), EXIT_ERROR) if desktop: # Claude Desktop's file is ours to write, owner-read-only (merge_mcp_server): the key goes in it, never on a # command line entry = mcp_server_entry(source, args.url, key, command) else: entry = mcp_run_entry(args, source) shown = "%s --from %s %s" % (command, source, MCP_PACKAGE) key_from = ("`lhbox mcp run` starts the server with LHBOX_API_KEY from Claude Code's environment, else the login " "saved for %s (profile %s)" % (url, active_profile())) snippet = {"mcpServers": {args.name: entry}} if args.print: print_json(mcp_masked(snippet, key)) if desktop: print("The key is masked. Without --print, `lhbox mcp install` writes the real one, " "from %s, into the host's configuration." % CRED_FILE_SHOWN, file=sys.stderr) else: print("The entry holds no key: %s." % key_from, file=sys.stderr) return if desktop: path = claude_desktop_config_path() backup = merge_mcp_server(path, args.name, entry) emit(args, {"client": "claude-desktop", "config": path, "backup": backup, "server": args.name, "transport": transport, "command": shown, "url": args.url.rstrip("/"), "api_key": mask_key(key), "next": "Restart Claude Desktop; the tools appear under '%s'." % args.name}) return claude = shutil.which("claude") if not claude: print_json(mcp_masked(snippet, key)) print("`claude` is not on PATH, so nothing was written. In a shell that has it, run\n" " claude mcp add-json --scope %s %s ''\n" "(it holds no key: %s)." % (args.scope, args.name, key_from), file=sys.stderr) return r = subprocess.run([claude, "mcp", "add-json", "--scope", args.scope, args.name, json.dumps(entry)], capture_output=True, text=True) said = ((r.stdout or "") + (r.stderr or "")).replace(key, mask_key(key)).strip() if r.returncode: die("claude mcp add-json failed (exit %d): %s" % (r.returncode, said), EXIT_ERROR) emit(args, {"client": "claude-code", "scope": args.scope, "server": args.name, "transport": transport, "command": shown, "url": url, "api_key": mask_key(key), "key_from": key_from, "claude_said": said, "next": "Start a new Claude Code session; `claude mcp list` shows it."}) def cmd_mcp_headers(args): """Claude Code's headersHelper for the entry `lhbox mcp install` writes (security review 2026-10-08, M8): one JSON object, {"Authorization": "Bearer "}, on stdout, the key as every command finds it (LHBOX_API_KEY, else the login saved for --url in --profile). For a program: on a terminal it refuses unless --show-key, since a key never reaches a terminal unasked. Sends nothing, and asks no site for a newer version (it runs at every connection).""" args.no_version_check = True if sys.stdout.isatty() and not args.show_key: die("`lhbox mcp headers` prints your API key as an Authorization header for Claude Code (an MCP entry's " "headersHelper runs it); it does not print a key to a terminal. --show-key prints it anyway.", EXIT_USAGE) key = api_key(args) sys.stdout.write(json.dumps({"Authorization": "Bearer " + key}) + "\n") def cmd_mcp_run(args): source = args.source or mcp_default_source() key = api_key(args) uvx = shutil.which("uvx") if not uvx: die("uvx is not on PATH. Install uv (https://docs.astral.sh/uv/), or run the server directly: " "pipx install %s && LHBOX_API_KEY=... %s" % (source, MCP_PACKAGE), EXIT_ERROR) problem = mcp_source_problem(source) if problem: # its own code (#1756): the input was fine, the stdio server is what is not available here remote = mcp_remote_url(args.url) or "https://mcp.lakehousebox.com/mcp" msg = "The MCP server cannot start from here: %s." % problem remedy = ("The hosted server needs nothing installed: `lhbox mcp install` configures it (%s); or pass --from a " "checkout's platform/mcp directory." % remote) if _json_mode(): die_json("mcp_server_unavailable", msg, EXIT_ERROR, remote_url=remote, remedy=remedy) die(msg + " " + remedy, EXIT_ERROR) env = dict(os.environ, LHBOX_URL=args.url.rstrip("/"), LHBOX_API_KEY=key) extra = [a for a in (args.server_args or []) if a != "--"] os.execve(uvx, [uvx, "--from", source, MCP_PACKAGE] + extra, env) class Parser(argparse.ArgumentParser): """argparse exits 2 on every usage error, which collided with 'limit or conflict'. A blown quota and a mistyped flag demand opposite responses, so they cannot share a code. Subclassing the top-level parser is enough: add_subparsers() propagates the class downwards. """ def parse_known_args(self, args=None, namespace=None): ns, rest = super().parse_known_args(args, namespace) # the global --url unset: LHBOX_URL, else the server the profile's saved login is for, else the managed service # (remembered_url); filled here so every caller of the parser gets a server, not only run() if hasattr(ns, "url") and ns.url is None and self.prog == "lhbox": saved = _PROFILE[0] _PROFILE[0] = getattr(ns, "profile", None) or saved try: ns.url = _env("URL") or remembered_url() or MANAGED_URL finally: _PROFILE[0] = saved return ns, rest def error(self, message): # an option or command this lhbox does not know may be one a newer lhbox has (feedback 2026-10-16: commands copied # from the current docs, refused by 0.6.7 as a typo): ask the site (2 s, once a day) and say so published = (_newer_published(fetch=True) if message.startswith("unrecognized arguments") or "invalid choice:" in message else None) if published: remedy = ("lhbox %s may predate this command line: %s is published. Run `%s`, then the same command; if it is " "still refused, see %s --help." % (__version__, published, _update_command(), self.prog)) else: remedy = "Fix the command line (%s --help); a retry unchanged fails the same way." % self.prog if _json_mode(): die_json("usage_error", "%s: error: %s" % (self.prog, message), EXIT_USAGE, usage=self.format_usage().strip(), remedy=remedy) self.print_usage(sys.stderr) die("%s: error: %s%s" % (self.prog, message, ("\n" + remedy) if published else ""), EXIT_USAGE) # Python 3.9's argparse asserts while WRAPPING a usage line whose mutually exclusive group holds suppressed members # (every `--catalog` with its hidden `--warehouse` twin): `catalog uploader create --help`, and every usage error of # ten commands, ended in "unexpected AssertionError" (2026-09-24; macOS's Xcode python3 is 3.9, and # pyproject says >=3.9). Fixed upstream in 3.10+. The fallback formats once more without wrapping. # Python 3.15 passes `file` (the stream whose colour support decides the help's colours): the arguments pass through, # or every --help ended in "unexpected TypeError: Parser._get_formatter() got an unexpected keyword argument 'file'" # (2026-10-22). _no_wrap = False def _get_formatter(self, *args, **kwargs): if self._no_wrap: return self.formatter_class(prog=self.prog, width=1_000_000) return super()._get_formatter(*args, **kwargs) def _unwrapped(self, fmt): try: return fmt() except AssertionError: self._no_wrap = True try: return fmt() finally: self._no_wrap = False def format_usage(self): return self._unwrapped(super().format_usage) def format_help(self): return self._unwrapped(super().format_help) class _NeedFullTree(Exception): """A lazily built command line reached a command it did not build: parse again with the whole tree.""" class _Unbuilt: """What `build_parser(only=...)` hands the code of a command it is not building: every call is a no-op that returns the same object, so the ~2,000 add_argument calls of the other commands cost nothing. Parsing through it is impossible by construction: it asks for the whole tree instead.""" def __getattr__(self, name): return self def __call__(self, *args, **kwargs): return self def __iter__(self): return iter(()) def __getitem__(self, key): return self def __setitem__(self, key, value): pass def parse_known_args(self, *args, **kwargs): raise _NeedFullTree() class _StubParser: """A command registered by name and help only (its parent's usage, help and `invalid choice` list are made of those, so they stay exactly the whole tree's); not a parser at all, since none of it is ever read. Selecting it means the guess of `_command_words` was wrong.""" def __init__(self, **kwargs): pass def _check_help(self, action): pass def parse_known_args(self, *args, **kwargs): raise _NeedFullTree() class _LazyParser(Parser): """A parser on the path being built: its subcommands build the next word of the path for real, the others as stubs.""" _lazy_path = None def add_subparsers(self, **kwargs): action = super().add_subparsers(**kwargs) return action if self._lazy_path is None else _OnlyCommand(action, self._lazy_path) class _OnlyCommand: """A subparsers action building the command `path[0]` names for real (its own subcommands after `path[1:]`), and its siblings as `_StubParser`s.""" def __init__(self, action, path): object.__setattr__(self, "_action", action) object.__setattr__(self, "_path", path) def add_parser(self, name, **kwargs): wanted = bool(self._path) and self._path[0] == name real = self._action._parser_class self._action._parser_class = _LazyParser if wanted else _StubParser try: parser = self._action.add_parser(name, **kwargs) finally: self._action._parser_class = real if wanted: parser._lazy_path = self._path[1:] return parser return _Unbuilt() def __getattr__(self, name): return getattr(self._action, name) def __setattr__(self, name, value): setattr(self._action, name, value) _LAZY_ALIASES = {"warehouse": "catalog"} # a name build_parser maps by hand onto another command's parser def _command_words(words): """The command a command line most likely names, for `build_parser(only=...)`: its words that are not options nor the value of a global option (`catalog list`, plus any positional values, which no parser asks for). A wrong guess costs a second parse with the whole tree, never a wrong answer; () when there is none (`lhbox --help` builds the root).""" path, i = [], 0 while i < len(words): w = words[i] if w == "--": break if w in ("--url", "--api-key", "--profile"): i += 2 continue if not w.startswith("-"): path.append(w) i += 1 return tuple(path) def _parse_command_line(argv, words): """Parse with only the command named built (one leaf and its parents instead of ~400 parsers: about 15 ms less per start), falling back to the whole tree whenever the lazy one reaches a command it did not build. Output, help and errors are the same either way: every parser on the path registers all its subcommands' names and help.""" try: return build_parser(only=_command_words(words)).parse_args(argv) except _NeedFullTree: return build_parser().parse_args(argv) def build_parser(only=None): """The whole command line, as data. `main()` runs it; platform/scripts/docs_build.py walks it to render the CLI reference, so the documentation cannot drift from what the parser accepts. `only`, a command's words (`("catalog", "list")`), builds that command and its parents for real and every other command as a stub (`_parse_command_line`).""" p = Parser( prog="lhbox", description="LakehouseBox: an open lakehouse you control.", # Raw, so the exit-code contract is not re-flowed: an agent greps these lines, and argparse's # default formatter would happily split "5 server or unreachable" across two of them. formatter_class=argparse.RawDescriptionHelpFormatter, epilog="Output is JSON when piped and a table on a terminal. Piped, stdout is one JSON document or nothing;\n" "every error is one JSON envelope on stderr {\"error\": {code, message, remedy, ...}}.\n" "Anywhere a project_id or a catalog's warehouse_id is accepted, the name works too.\n" "\n" "Exit codes, one meaning each:\n" " 0 ok\n" " 1 invalid input the values you sent are wrong; fix them, do not retry\n" " 2 limit/conflict a real quota or a real 409; change the plan\n" " 3 auth key missing, wrong or revoked\n" " 4 not found no such project, catalog, namespace or table\n" " 5 server or unreachable retry with backoff, unless the error's outcome is \"unknown\":\n" " the request may have completed; check first (the remedy says how)\n" " 6 usage error the command line is malformed; fix it, do not retry\n" "\n" "A bug in LakehouseBox itself: lhbox bug --title \"...\" (the public tracker's form, filled in; nothing sent).\n") p.add_argument("--version", action="version", version="lhbox %s (build %s)" % (__version__, cli_build())) p.add_argument("--url", default=None, help="API base URL (env LHBOX_URL; else the one server the profile's saved login is for; else %s)" % MANAGED_URL) p.add_argument("--api-key", help="API key (env LHBOX_API_KEY). Kept for scripts, but a key on a command line is " "visible to other local users in the process list (ps) while the command runs: " "prefer LHBOX_API_KEY or the login `lhbox login` saves") p.add_argument("--profile", help="the saved login to use, one per account or organisation on this machine " "(env LHBOX_PROFILE; `lhbox profile use` sets the default; see `lhbox profile list`)") p.add_argument("--json", action="store_true", help="force JSON output") p.add_argument("--human", action="store_true", help="force human-readable output") p.add_argument("--reason", help="why this change is made, kept with it in the object history (lhbox history); " "env LHBOX_REASON") p.add_argument("--ref", help="a link to where the change was decided (a pull request, an issue), kept with it; env LHBOX_REF") sub = p.add_subparsers(dest="cmd", required=True) if only is not None: only = tuple(only) sub = _OnlyCommand(sub, (_LAZY_ALIASES.get(only[0], only[0]),) + only[1:] if only else only) def add_idem(sp): sp.add_argument("--idempotency-key", help="any string; safe to reuse when retrying the same call") c = sub.add_parser("signup", help="create your account and catalog: email -> code -> API key") c.add_argument("--email", required=True) c.add_argument("--workspace", help="workspace name (default: the part before @)") c.add_argument("--full-name", dest="full_name", help="your name, for the account") c.add_argument("--organization", help="organisation name; with --handle the organisation is reserved now") c.add_argument("--handle", help="the organisation's handle (lakehousebox.com/app/; lowercase letters, digits, dashes; fixed after signup)") c.add_argument("--code", help="the code you received; prompted for if omitted") c.add_argument("--engine", default="duckdb", choices=("duckdb", "pyiceberg", "spark")) c.add_argument("--save", action="store_true", help="store the API key in %s; with it the key is NOT printed" % CRED_FILE_SHOWN) c.add_argument("--show-key", dest="show_key", action="store_true", help="print the API key even when it was saved (default: a saved key stays out of the terminal)") c.add_argument("--accept-terms", action="store_true", help="accept the Terms of Service and Privacy Policy") c.set_defaults(fn=cmd_signup) c = sub.add_parser("terms", help="the Terms version in force and whether you accepted it") c.add_argument("--accept", action="store_true"); c.set_defaults(fn=cmd_terms) c = sub.add_parser("account", help="your account").add_subparsers(dest="sub", required=True) c2 = c.add_parser("delete", help="delete your account: keys revoked now, data purged within 30 days", description="DELETE /v1/me. A person's account asks for its current password, and for a code when " "two-factor authentication is on: give them with --password and --code, or type them " "when asked at a terminal. A token confirms with its principal_id and needs neither. " "A person in several organisations first leaves or deletes them one at a time " "(Settings > Account > Danger zone on the account page).") c2.add_argument("--confirm", required=True, help="your email, typed out") c2.add_argument("--password", metavar="@FILE|@-", help="your current password from a file or stdin, never inline; asked for at a terminal when needed") c2.add_argument("--password-env", dest="password_env", metavar="VAR", help="the environment variable holding your current password") c2.add_argument("--code", help="a code from your authenticator app (or a backup code), when two-factor is on") c2.set_defaults(fn=cmd_account_delete) c = sub.add_parser("login", help="sign this computer in as you: allow it in your browser (or with a code: --no-browser). " "The key acts as you, as on the website, for 30 days; it is saved here, never printed. " "A key limited to some catalogs is made on the website (Settings > Access keys)") c.add_argument("--issuer", nargs="?", const="", default=None, metavar="ISSUER", help="log in through an external OpenID Connect issuer instead of the LakehouseBox login (the first " "configured one, or the one named); for self-hosted deployments with their own identity provider") c.add_argument("--sso", metavar="EMAIL", help="log in with your organisation's own identity provider (e.g. Microsoft Entra ID), found from your " "work address") c.add_argument("--label", default="cli", help="API key label on the --issuer and --sso paths (the LakehouseBox login labels it cli )") c.add_argument("--name", help="the token's name shown on the consent screen and in Connections (default: this machine's hostname)") # no longer used (2026-11-02: a login is yes or no and acts as the person); accepted so older scripts keep working c.add_argument("--level", choices=("read", "write"), default=None, help=argparse.SUPPRESS) c.add_argument("--manage-agents", action="store_true", help=argparse.SUPPRESS) c.add_argument("--no-browser", action="store_true", help="sign in with a code instead of opening a browser here (the browser is on another computer: an " "SSH session, a server). Either way the key acts as you, for 30 days") add_catalog_flag(c, action="append", metavar="CATALOG[:LEVEL]", hidden=True) # no longer used, as --level c.add_argument("--campaign", metavar="SOURCE[/MEDIUM[/CAMPAIGN[/CONTENT]]]", help="the campaign tags of the link that brought you here (the site writes them into the command it shows); " "an account created on the approval page is attributed to them") c.add_argument("--new", action="store_true", help="start a new authorisation even when the saved key still works") c.add_argument("--no-wait", dest="no_wait", action="store_true", help="print the page and the code, keep the pending login in the credentials file (pending_device) and exit 0; " "finish it later with --resume (the code lives an hour, not 15 minutes)") c.add_argument("--resume", action="store_true", help="poll the pending login left by --no-wait once: connected (exit 0), or still pending (exit 3, the credential is " "still missing); --resume --wait polls until the person decides") c.add_argument("--wait", action="store_true", help="with --resume: wait for the approval instead of polling once (the default " "`lhbox login` waits anyway, up to the code's 15 minutes)") c.add_argument("--engine", default="duckdb") c.add_argument("--save", action="store_true", help="kept for compatibility: the key is always saved to %s" % CRED_FILE_SHOWN) c.add_argument("--show-key", dest="show_key", action="store_true", help="print the API key as well (default: it is saved and never shown; an agent should not need it)") c.add_argument("--accept-terms", action="store_true", help="accept the Terms of Service on first login (--issuer path)") # a service account's sign-in (platform/docs/service-accounts.md): an enterprise feature, unlisted until it is sold c.add_argument("--client-credentials", dest="client_credentials", action="store_true", help=argparse.SUPPRESS) c.add_argument("--client-id", dest="client_id", help=argparse.SUPPRESS) c.add_argument("--client-secret-env", dest="client_secret_env", metavar="VAR", help=argparse.SUPPRESS) c.add_argument("--scope", help=argparse.SUPPRESS) c.add_argument("--client-auth", dest="client_auth", choices=("post", "basic"), default="post", help=argparse.SUPPRESS) c.set_defaults(fn=cmd_login) # `new` and `status` stay out of the help and the docs until the service offers them (research/70; rule 10) c = sub.add_parser("new", help="no account yet: a catalog for this agent now; a person claims it later", description="no account yet: a catalog for this agent now, write access, the key saved here; a person " "claims it later or it is deleted with its data after 72 h. Running it accepts the Terms") c.add_argument("--force", action="store_true", help="replace the key already saved for this API (default: refused)") c.add_argument("--campaign", metavar="SOURCE[/MEDIUM[/CAMPAIGN[/CONTENT]]]", help="the campaign tags of the link that brought you here (the site writes them into the command it shows)") c.set_defaults(fn=cmd_new) c = sub.add_parser("claim", help="a person keeps the catalog `lhbox new` made: a link and a code for them", description="a person keeps the catalog `lhbox new` made: prints a link and a code for them; --wait " "waits for their decision and saves this machine's new key") c.add_argument("--wait", action="store_true", help="wait for the person's decision (default: print and exit; --resume later)") c.add_argument("--resume", action="store_true", help="collect a claim started earlier (polls once; with --wait until decided)") c.set_defaults(fn=cmd_claim) c = sub.add_parser("status", help="the time an unclaimed catalog (lhbox new) has left", description="whether this machine's catalog is still unclaimed (lhbox new), and the time it has left") c.set_defaults(fn=cmd_status) c = sub.add_parser("discard", help="end an unclaimed catalog (lhbox new) now: it is deleted with its data and every key, " "as at its expiry, and this machine forgets the key", description="DELETE /v1/agent/identity: the unclaimed organisation `lhbox new` made, its catalog with " "every table and file, and its keys, deleted now instead of at expires_at. For a key that " "leaked, or a catalog nobody needs. A catalog a person has claimed is theirs: refused.") add_yes(c, "discarding the catalog and its data") c.set_defaults(fn=cmd_discard) c = sub.add_parser("recover", help="retired: says how to get back in (reset the password, or `lhbox login` again)") # the old flags are still accepted, so an old script gets the remedy instead of a usage error c.add_argument("--email", help=argparse.SUPPRESS); c.add_argument("--code", help=argparse.SUPPRESS) c.add_argument("--save", action="store_true", help=argparse.SUPPRESS) c.add_argument("--show-key", dest="show_key", action="store_true", help=argparse.SUPPRESS) c.set_defaults(fn=cmd_recover) ak = sub.add_parser("api-key", help="API keys of the caller").add_subparsers(dest="sub", required=True) c = ak.add_parser("create"); c.add_argument("--label", default="cli"); c.set_defaults(fn=cmd_apikey_create) c = ak.add_parser("list"); c.set_defaults(fn=cmd_apikey_list) c = ak.add_parser("revoke"); c.add_argument("--key-id", required=True); add_yes(c, "the revocation", takes_name=True); c.set_defaults(fn=cmd_apikey_revoke) # metavar: the public verbs only; `scim-token` (an enterprise feature, unlisted until it is sold) stays out of the help og = sub.add_parser("org", help="organisations: members, domains, invitations").add_subparsers( dest="sub", required=True, metavar="{list,members,invite,accept,domain,offers,join,set,role}") c = og.add_parser("list"); c.set_defaults(fn=cmd_org_list) c = og.add_parser("members"); c.add_argument("--org"); c.set_defaults(fn=cmd_org_members) c = og.add_parser("invite", help="invite a person by email, as a member or an admin; --catalog gives a member the " "catalogs they should read or write on joining (a member reads none until given access)") c.add_argument("--org"); c.add_argument("--email", required=True) c.add_argument("--role", default="member", choices=("member", "admin")) c.add_argument("--catalog", action="append", metavar="NAME[:read|write]", help="a catalog the person is given when they join, at read (the default) or write; repeatable, at " "most 20. Without it a member reads only the catalogs open to the whole organisation. Not with " "--role admin: an admin writes every catalog by role") c.set_defaults(fn=cmd_org_invite) c = og.add_parser("accept"); c.add_argument("--token", required=True); c.set_defaults(fn=cmd_org_accept) c = og.add_parser("domain", help="claim your organisation's email domain (admin; it takes effect only once a DNS TXT " "record verifies it), --verify the claim, or --remove it") c.add_argument("--org"); c.add_argument("--domain", required=True) mode = c.add_mutually_exclusive_group() mode.add_argument("--verify", action="store_true", help="look up the TXT record _lakehousebox. and verify the claim") mode.add_argument("--remove", action="store_true", help="release the domain instead of claiming it (admin); " "domain join switches off when no verified domain remains") c.set_defaults(fn=cmd_org_domain) c = og.add_parser("offers", help="organisations you may join because they verified and opened your address's domain") c.set_defaults(fn=cmd_org_offers) c = og.add_parser("join", help="accept a domain offer: join that organisation as a member (nothing joins you otherwise)") c.add_argument("--org", help="the offering organisation's handle (optional when you have exactly one offer)") c.set_defaults(fn=cmd_org_join) c = og.add_parser("set"); c.add_argument("--org"); c.add_argument("--name") c.add_argument("--domain-join", dest="domain_join", choices=("on", "off"), help="offer membership to people on a verified domain (they join only if they accept)") c.add_argument("--deprovision", choices=("tokens", "everything"), help="what removing a member stops: their tokens and connections (tokens, the default), or also the " "sinks, blob uploaders and hosted agents they made (everything)") c.set_defaults(fn=cmd_org_set) c = og.add_parser("policy", help="what the organisation's members may do: publish catalogs, connect agents, create " "hosted agents (read it; an admin changes it with the flags)") c.add_argument("--org", help=ORG_HELP) c.add_argument("--publish-catalogs", dest="publish_catalogs", choices=("admins", "members", "nobody"), help="who may make a catalog public: admins (the default), members too (on a catalog they can " "write), or nobody; catalogs public now stay public") c.add_argument("--connect-agents", dest="connect_agents", choices=("members", "admins"), help="who may connect agents: tokens, `lhbox login`, MCP clients, personal API keys (default members)") c.add_argument("--hosted-agents", dest="hosted_agents", choices=("members", "admins"), help="who may create hosted agents (default members)") c.add_argument("--new-catalogs", dest="new_catalogs", choices=("restricted", "organisation"), help="the general access a new catalog starts with: restricted (the default: only the people and " "tokens given access read it) or organisation (every member reads it); its creator may say " "otherwise, and catalogs that exist are unchanged") # who may create connections (members, the default, or admins; plane/sources.py): hidden while sources are unlisted c.add_argument("--create-connections", dest="create_connections", choices=("members", "admins"), help="who may create connections (lhbox connection): members (the default) or admins") c.add_argument("--session-lifetime", dest="session_lifetime", choices=("30d", "7d", "12h"), help="how long members stay signed in on the account page: 30d (until 30 days without use, the " "default), 7d or 12h (that long after signing in); a person in several organisations gets the " "shortest. API keys and connected agents are not affected") c.set_defaults(fn=cmd_org_policy) c = og.add_parser("role", help="change a member's role: admin or member (an organisation keeps at least one admin)") c.add_argument("--org", help=ORG_HELP); c.add_argument("--principal", required=True) c.add_argument("--role", required=True, choices=("admin", "member")); c.set_defaults(fn=cmd_org_role) st = og.add_parser("scim-token", description="The organisation's SCIM tokens (an enterprise feature): the bearer your identity " "provider presents at the SCIM URL to provision and deprovision people.").add_subparsers( dest="sub2", required=True) c = st.add_parser("create", help="a new SCIM token, shown once (admin; at most 2 live)") c.add_argument("--org", help=ORG_HELP); c.add_argument("--label"); c.set_defaults(fn=cmd_org_scim_token_create) c = st.add_parser("list", help="the organisation's SCIM tokens, never their secrets") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_org_scim_token_list) c = st.add_parser("revoke", help="revoke a SCIM token: the identity provider's next request with it is refused") c.add_argument("token_id"); c.add_argument("--org", help=ORG_HELP) add_yes(c, "the revocation"); c.set_defaults(fn=cmd_org_scim_token_revoke) gr = og.add_parser("group-rules", description="The organisation's group rules (an enterprise feature): a directory group synced " "through SCIM, named by its externalId or SCIM id, gives its members the admin role, a " "catalog level or a namespace level.").add_subparsers(dest="sub2", required=True) c = gr.add_parser("set", help="replace the whole rule set from a JSON file (a person who is an admin)") c.add_argument("--org", help=ORG_HELP) c.add_argument("--file", required=True, help='JSON: {"rules": [...]} or the list itself, - for stdin') c.set_defaults(fn=cmd_org_group_rules_set) c = gr.add_parser("list", help="the rules, each with its group's current name and member count") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_org_group_rules_list) c = gr.add_parser("clear", help="remove every rule: what they gave is revoked, hand-made grants stay") c.add_argument("--org", help=ORG_HELP) add_yes(c, "removing every rule"); c.set_defaults(fn=cmd_org_group_rules_clear) sa = og.add_parser("service-account", description="The organisation's service accounts (an enterprise feature): an application of your " "organisation's own identity provider -- an Entra application or managed identity, an " "Okta service app -- that an unattended agent signs in as with that provider's " "client-credentials tokens. The organisation owns it: no person's departure stops it; " "deleting it here, or disabling the application in the directory, does.").add_subparsers( dest="sub2", required=True) c = sa.add_parser("create", help="register an application of your identity provider (a person who is an admin); grant " "it catalogs afterwards with lhbox catalog grant") c.add_argument("name", help="the service account's name: a lowercase word (a-z, 0-9, - and _)") who = c.add_mutually_exclusive_group(required=True) who.add_argument("--subject", help="the application as its tokens name it: Entra, its service principal's object id (Enterprise " "applications -> Object ID); another provider, its client id") who.add_argument("--google-token", metavar="TOKEN", help="a Google Cloud workload instead (a VM, Cloud Run, GKE, a scheduled job): an ID token of its " "Google service account for this install, as proof you control it, or - to read it from stdin " "(gcloud auth print-identity-token --impersonate-service-account= --audiences=); the workload then sends its " "own ID token, no key") c.add_argument("--description"); c.add_argument("--org", help=ORG_HELP) c.set_defaults(fn=cmd_org_service_account_create) c = sa.add_parser("list", help="the organisation's service accounts, with their grants and last use") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_org_service_account_list) c = sa.add_parser("delete", help="delete a service account: its next request is refused and its grants go (admin)") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP) add_yes(c, "the deletion"); c.set_defaults(fn=cmd_org_service_account_delete) # unlisted (enterprise features, research/74): out of the help's command list, where help=SUPPRESS still printed it og._choices_actions[:] = [a for a in og._choices_actions if a.dest not in ("scim-token", "group-rules", "service-account")] # `lhbox agent` was the tokens' command until 0.4.0 (2026-09-29); the word now belongs to hosted agents (research/47), # whose commands come with their harness. Until then it says where the tokens went and sends nothing (not a # compatibility layer: nothing runs; high review of #752) ha = sub.add_parser("agent", help="hosted agents, in preview for the organisations it is enabled for (tokens, which this " "command managed until 0.4.0, are `lhbox token`)", description="Hosted agents: a prompt LakehouseBox runs for you next to your data, on the provided " "model, reading the catalogs you grant it; runs count against your organisation's monthly " "tokens and runs per day.").add_subparsers( dest="sub", required=True, metavar="{create,list,show,update,run,runs,subscribe,unsubscribe,delete}") REF_HELP = "the agent's name, or its agent_id (needed when you belong to two organisations with an agent of that name)" def agent_fields(c, creating): c.add_argument("--prompt", metavar="TEXT", required=creating, help="what the agent does: inline, @file or @- (stdin)") c.add_argument("--catalog", dest="catalog", action="append", metavar="CATALOG", help="a catalog the agent may read (repeat; its grants become exactly these)") c.add_argument("--warehouse", dest="catalog", action="append", metavar="CATALOG", help=argparse.SUPPRESS) c.add_argument("--state-key", action="append", metavar="KEY", help="a small value it may remember between runs (repeat)") c.add_argument("--topic", action="append", metavar="TOPIC", help="a memory topic: the agent keeps notes about items in " "it (note, resolve, flag_owner) and starts each run from their view (repeat; up to 12)") g = c.add_mutually_exclusive_group() g.add_argument("--notify-owner", dest="notify_owner", action="store_true", default=None, help="it may email you (its creator's person) once per run") g.add_argument("--no-notify-owner", dest="notify_owner", action="store_false", help="it may not email") g = c.add_mutually_exclusive_group() g.add_argument("--artifacts", dest="artifacts", action="store_true", default=None, help="it may publish artifacts (pages for people) and the next versions of the ones it keeps" + (" (the default for a new agent)" if creating else "")) g.add_argument("--no-artifacts", dest="artifacts", action="store_false", help="it may not publish artifacts") c.add_argument("--run-seconds", type=int, metavar="S", help="one run's wall time (at most the organisation's limit)") c.add_argument("--max-tool-calls", type=int, metavar="N", help="tool calls one run may make (default 30, at most the organisation's limit); the last few are " "kept for the agent to save its memory and notify") c.add_argument("--model", metavar="MODEL", help="a provided model (default deepseek-v4-flash)") c.add_argument("--schedule", metavar="CRON", help='when it runs by itself: five cron fields, e.g. "0 7 * * *" (at most ' "hourly and the organisation's runs per day)") c.add_argument("--tz", metavar="ZONE", help="the schedule's time zone, e.g. Europe/Madrid (default UTC)") c.add_argument("--integration", action="append", metavar="NAME:TOOL[,TOOL]", help="an integration you connected and the tools the agent may call there (repeat; the list " "becomes exactly these), e.g. github:search_issues,get_file_contents. Your own sign-in only: " "a token (an lhbox login connection included) is refused integration_needs_person; attach it " "on the account page") c.add_argument("--write", action="append", metavar="CATALOG.NS.TABLE", help="a table the agent may append rows to (repeat; the list becomes exactly these): in a catalog " "it reads, and you need write there") c.add_argument("--on-commit", action="append", metavar="CATALOG.NS.TABLE", help="run the agent when this table gets a new snapshot (repeat, up to 5; the list becomes exactly " "these): in a catalog it reads, not one it writes; at most once per shortest schedule " "interval (hourly), within the organisation's runs per day") c.add_argument("--on-commit-if", metavar="SQL", help="with --on-commit: run only when this read-only SQL's first column is true (a boolean true or " "a number other than 0), checked when a watched table changed, as the agent itself (it reads " "what the agent reads), one row, at most every 15 minutes; e.g. \"SELECT max(day) > " "current_date - 1 FROM bde.core.observaciones\"") c.add_argument("--allow-host", action="append", metavar="HOST", help="a web host the agent may fetch (https GET; repeat): its web hosts become exactly these, " "with the keys given by --host-credential in the same command (no other key is kept)") c.add_argument("--host-credential", action="append", metavar="HOST=INTEGRATION", help="send that web key (lhbox integration add NAME --web-key) to HOST; the host is allowed too " "(alone on update: added to the agent's hosts and keys). Like --integration, your own sign-in " "only (a token is refused)") c = ha.add_parser("create", help="a new agent with its own key-less identity reading the catalogs given") c.add_argument("name", metavar="NAME", help="the agent's name (lowercase letters, digits and _)") agent_fields(c, True) c.add_argument("--org", metavar="ORG_ID", help="the organisation (when you belong to several)") c.set_defaults(fn=cmd_agent_create) c = ha.add_parser("list", help="your organisation's agents and its allowance (tokens this month, runs today)") c.add_argument("--org", metavar="ORG_ID", help="the organisation (when you belong to several)") c.set_defaults(fn=cmd_agent_list) c = ha.add_parser("models", help="the models LakehouseBox provides: where they run, whether they see images, price") c.set_defaults(fn=cmd_agent_models) c = ha.add_parser("show", help="one agent: its definition, catalogs and last run") c.add_argument("name", metavar="NAME", help=REF_HELP) c.set_defaults(fn=cmd_agent_show) c = ha.add_parser("update", help="a new version of the agent (only what you pass changes), or --pause / --resume") c.add_argument("name", metavar="NAME", help=REF_HELP) agent_fields(c, False) c.add_argument("--no-catalogs", action="store_true", help="take away every catalog grant (with no --catalog)") c.add_argument("--no-state-keys", action="store_true", help="forget every state key (with no --state-key)") c.add_argument("--no-topics", action="store_true", help="turn its memory topics off (its notes are kept)") c.add_argument("--no-schedule", action="store_true", help="remove the schedule: it runs on demand only") c.add_argument("--no-integrations", action="store_true", help="detach every integration (with no --integration)") c.add_argument("--no-writes", action="store_true", help="the agent appends to no table (with no --write)") c.add_argument("--no-on-commit", action="store_true", help="no table's new snapshot starts a run (with no --on-commit)") c.add_argument("--no-on-commit-if", action="store_true", help="a watched table's new snapshot starts a run without a condition") c.add_argument("--no-web", action="store_true", help="the agent fetches no web host (with no --allow-host)") c.add_argument("--confirm-definition", action="store_true", help="approve the agent's current definition as yours, so it may use your integrations (needed when " "another credential, e.g. a token, wrote it; your own sign-in only)") g = c.add_mutually_exclusive_group() g.add_argument("--pause", action="store_true", help="no run starts until --resume") g.add_argument("--resume", action="store_true", help="runs may start again") c.add_argument("--restore-version", metavar="VERSION", help="put an earlier definition back whole (its id is in the mail sent when a key changes the agent)") c.set_defaults(fn=cmd_agent_update) c = ha.add_parser("run", help="run the agent now (one run at a time; counts against today's runs and the month's tokens)") c.add_argument("name", metavar="NAME", help=REF_HELP) c.add_argument("--dry-run", action="store_true", help="a test run: its tools read for real, its email and memory writes " "are shown, not performed; outside today's runs (its own daily cap), tokens still count") c.add_argument("--wait", action="store_true", help="wait for the run to end and print its final message") c.add_argument("--timeout", type=int, default=600, metavar="S", help="how long --wait waits (default 600 s)") c.set_defaults(fn=cmd_agent_run) c = ha.add_parser("brief", help="what needs you first (its flags, decisions due, failures, missed runs), then its memory " "as it sees it and its recent runs; no model") c.add_argument("name", metavar="NAME", help=REF_HELP) c.set_defaults(fn=cmd_agent_brief) c = ha.add_parser("talk", help="talk to the agent: it answers from its memory and runs, and may propose a new prompt " "or items to mark done, which change nothing until you say yes in your next message") c.add_argument("name", metavar="NAME", help=REF_HELP) c.add_argument("message", nargs="?", metavar="MESSAGE", help="what you say (omit it to list the latest exchanges)") c.add_argument("--about", metavar="TOPIC/ITEM", help="reply to an entry of its brief ([topic/item] there)") c.add_argument("--limit", type=int, default=5, metavar="N", help="how many exchanges to list (default 5)") c.set_defaults(fn=cmd_agent_talk) c = ha.add_parser("runs", help="the agent's runs: state, tokens, model requests, errors") c.add_argument("name", metavar="NAME", help=REF_HELP) c.add_argument("--limit", type=int, default=20, metavar="N") c.add_argument("--detail", action="store_true", help="each run's tool calls (with their SQL), emails and memory changes") c.set_defaults(fn=cmd_agent_runs) c = ha.add_parser("subscribe", help="email me this agent's notices (you need read on every catalog it reads and a " "verified address)") c.add_argument("name", metavar="NAME", help=REF_HELP) c.set_defaults(fn=cmd_agent_subscribe) c = ha.add_parser("unsubscribe", help="stop emailing me this agent's notices") c.add_argument("name", metavar="NAME", help=REF_HELP) c.set_defaults(fn=cmd_agent_unsubscribe) c = ha.add_parser("delete", help="delete the agent for good: its identity is suspended, its runs stay readable") c.add_argument("name", metavar="NAME", help=REF_HELP) add_yes(c, "the deletion") c.set_defaults(fn=cmd_agent_delete) c = ha.add_parser("revoke", help=argparse.SUPPRESS) c.add_argument("ref", nargs="?", default="") c.add_argument("rest", nargs=argparse.REMAINDER, help=argparse.SUPPRESS) c.set_defaults(fn=cmd_agent_renamed) ar = sub.add_parser("artifact", help="artifacts: pages an agent publishes for people, reading your catalogs live " "(publish, pull, ls, delete, restore)", description="An artifact is a page (a dashboard, a report, a map) published for people of your " "organisation. Its script reads the catalogs it names live, in the browser of " "whoever opens it, with that person's own permissions. It is private to its owner " "until they share it on the account page. A deleted one stays in the trash 30 days " "(lhbox artifact ls --deleted, lhbox artifact restore). How to write one: " "https://lakehousebox.com/docs/artifacts").add_subparsers( dest="sub", required=True, metavar="{publish,pull,ls,delete,restore}") c = ar.add_parser("publish", help="publish a page (one HTML file, or a folder) as a new artifact or the next version of one", description="Publish PAGE: one HTML file, or a folder holding index.html and the page's other files " "(.css .js .json .geojson .csv .svg, sub-folders allowed). A folder written by `lhbox " "artifact pull` (page/, assets/, artifact.json) publishes the next version of that " "artifact; a folder published as a new artifact gets that artifact.json too, so " "publishing it again makes its next version. Images, fonts and other assets go in " "assets/ beside page/ and are referred to as ../assets/; they are stored under " "their content hash and the page's references rewritten to match. A version is the " "whole page: what is not sent is not in it.") c.add_argument("page", metavar="PAGE", help="an HTML file, or a folder with index.html in it (or in its page/ folder)") c.add_argument("--title", metavar="TEXT", help="the page's title (1 to 200 characters): needed for a new artifact; " "with --artifact it renames it") c.add_argument("--catalog", dest="catalog", action="append", metavar="CATALOG", help="a catalog the page's SQL reads, by name or id; / for another organisation's " "public catalog (repeat). You must read each as a whole. With --artifact and no catalog " "named, it keeps the catalogs of the version before") c.add_argument("--warehouse", dest="catalog", action="append", metavar="CATALOG", help=argparse.SUPPRESS) c.add_argument("--no-catalogs", action="store_true", help="the page reads no catalog") c.add_argument("--artifact", metavar="ID", help="publish the next version of this artifact instead of a new one " "(a pulled folder's artifact.json names it)") c.add_argument("--note", metavar="TEXT", help="one line saying what this version changed (at most 200 characters)") c.add_argument("--description", metavar="TEXT", help="one line a link preview of the public page shows under its title " "(at most 300 characters); kept in artifact.json for the next publish") c.add_argument("--thumbnail", metavar="FILE", help="an image in the folder's assets/ (1200x630 PNG, JPEG or WebP is what " "previews show best): the public page's share image; kept in " "artifact.json for the next publish") c.add_argument("--org", metavar="ORG_ID", help="the organisation a new artifact is for, when its catalogs do not say " "(a page that reads only public catalogs)") c.set_defaults(fn=cmd_artifact_publish) c = ar.add_parser("pull", help="write an artifact's current version into a folder, to read it or change it", description="Write the current version's files into DIR: page/ (index.html and the page's other " "files), assets/ and artifact.json. Change them and publish the folder again with " "`lhbox artifact publish DIR`. For an artifact you may open, or one this key published.") c.add_argument("artifact", metavar="ARTIFACT", help="the artifact's id (8 letters and digits), as `lhbox artifact ls` names it") c.add_argument("dir", metavar="DIR", nargs="?", help="the folder to write into (default: one named after the title)") c.add_argument("--force", action="store_true", help="write into DIR even when it holds files (a file already " "there that the version does not have stays: use an empty " "folder for an exact copy)") c.set_defaults(fn=cmd_artifact_pull) c = ar.add_parser("check", help="check an artifact's current version without running it: missing files, catalogs " "nobody reads through it, the publish's warnings, its size", description="Check ARTIFACT's current version as published: the files its page files refer to " "(src and href, CSS url() and @import, relative imports, lhbox.asset with a literal " "path) that the version does not hold; the catalogs it names that nobody reads through " "it; absolute addresses in any page file that the page's frame blocks, by file and " "line; the publish's warnings; its size against the limits. The page is not run: " "console errors and query timings show in the browser's developer tools on the open " "page. Exit 1 when there is a problem (warnings do not count), so a CI step can gate " "on it. Given a file or folder on disk instead, it checks what a publish of it would " "refuse (a file type assets/ or the page does not take), before anything is sent.") c.add_argument("artifact", metavar="ARTIFACT", help="the artifact's id (8 letters and digits), as `lhbox artifact ls` " "names it; or a file or folder on disk, checked before it is " "published (what the publish would refuse; nothing is sent). A " "folder named like an id is written as a path: ./Ab12Cd34") c.set_defaults(fn=cmd_artifact_check) c = ar.add_parser("ls", help="the artifacts you can see: yours and your agents', those shared with you; a token's own") c.add_argument("--org", metavar="ORG_ID", help="only this organisation's (when you belong to several)") c.add_argument("--deleted", action="store_true", help="the trash instead: those deleted less than 30 days ago, which " "`lhbox artifact restore` brings back") c.set_defaults(fn=cmd_artifact_ls) c = ar.add_parser("delete", help="delete an artifact: into the trash, restorable for 30 days", description="Delete ARTIFACT: nobody opens it from now (its address answers as if it never " "existed), and it can be restored for 30 days with the same id and address (`lhbox " "artifact restore`, or the account page), then its files are removed. A person deletes " "their own artifacts (an admin, any of the organisation's); an agent's key deletes what " "it may publish to (the ones it made). Deleting a public page or one shared with people " "is allowed: the answer says who lost access, and when an agent or an admin deleted it, " "its owner is told by mail. Sharing and duplicating stay a person's, on the account page.") c.add_argument("artifact", metavar="ARTIFACT", help="the artifact's id (8 letters and digits), as `lhbox artifact ls` names it") c.add_argument("--yes", dest="yes", action="store_true", help="do not ask (scripts and agents): it can be restored for 30 " "days. Asked on a terminal otherwise") c.add_argument("--confirm", dest="confirm", nargs="?", const=True, metavar="NAME", help=argparse.SUPPRESS) c.set_defaults(fn=cmd_artifact_delete) c = ar.add_parser("restore", help="bring back an artifact from the trash (deleted less than 30 days ago)", description="Restore ARTIFACT from the trash: the same id, address and versions. It comes back " "private, whatever it was; the people it was shared with by name keep it. `lhbox " "artifact ls --deleted` lists the trash. Who may: as for deleting it.") c.add_argument("artifact", metavar="ARTIFACT", help="the artifact's id (8 letters and digits)") c.set_defaults(fn=cmd_artifact_restore) hi = sub.add_parser("integration", help="integrations: MCP servers your hosted agents may use, as you; in preview for " "the organisations hosted agents are enabled for", description="Integrations connect any MCP server to your organisation: with its sign-in (you approve " "in a browser where you are signed in to LakehouseBox), an API key, or none; the CLI " "never receives a token. Attach one to an agent on the account page, or with `lhbox " "agent update NAME --integration NAME:tool,...` signed in as yourself (a token cannot " "attach your integrations; lhbox integration show NAME lists its tools)." ).add_subparsers(dest="sub", required=True) def consent_flags(c): c.add_argument("--wait", action="store_true", help="wait until you approved in the browser (or it failed)") c.add_argument("--timeout", type=int, default=600, metavar="S", help="how long --wait waits (default 600 s)") c.add_argument("--open", action="store_true", help="also open the link in this machine's browser") c = hi.add_parser("add", help="connect an MCP server: prints the link to approve in your browser") c.add_argument("name", metavar="NAME", help="the integration's name (e.g. linear; lowercase letters, digits and _)") c.add_argument("--mcp", metavar="URL", help="the MCP server's URL (https; for the name github: GitHub's MCP server " "by default)") c.add_argument("--api-key-stdin", action="store_true", help="the server takes an API key: read it from stdin (it is " "stored sealed and never shown again)") c.add_argument("--header", "--header-name", dest="header", metavar="NAME", help="with --api-key-stdin: the header " "the key goes in (default Authorization, sent as 'Bearer ')") c.add_argument("--web-key", action="store_true", help="a web API's key for an agent's fetch_url (with --host and " "--api-key-stdin), not an MCP server") c.add_argument("--host", metavar="HOST", help="with --web-key: the one host the key is sent to") c.add_argument("--key-param", metavar="NAME", help="with --web-key: send the key as this query parameter instead " "of a header") c.add_argument("--scope", action="append", metavar="SCOPE", help="narrow the scopes asked for (repeat); default: the " "server's own") c.add_argument("--org", metavar="ORG_ID", help="the organisation (when you belong to several)") consent_flags(c) c.set_defaults(fn=cmd_integration_add) c = hi.add_parser("list", help="your organisation's integrations and their state") c.add_argument("--org", metavar="ORG_ID", help="the organisation (when you belong to several)") c.set_defaults(fn=cmd_integration_list) c = hi.add_parser("show", help="one integration: its server, tools, scopes and state") c.add_argument("ref", metavar="NAME", help="the integration's name or id") c.set_defaults(fn=cmd_integration_show) c = hi.add_parser("reconnect", help="approve again (after `needs_reauth`, or to switch accounts)") c.add_argument("ref", metavar="NAME", help="the integration's name or id") consent_flags(c) c.set_defaults(fn=cmd_integration_reconnect) c = hi.add_parser("wait", help="wait until the person approved (after add or reconnect; their answer's wait_command)") c.add_argument("ref", metavar="NAME", help="the integration's name or id") c.add_argument("--previous", metavar="CONNECTED_AT", help="its connected_at before the approval ('-' for never), " "from the add or reconnect answer") c.add_argument("--timeout", type=int, default=600, metavar="S", help="how long to wait (default 600 s)") c.set_defaults(fn=cmd_integration_wait) c = hi.add_parser("delete", help="delete the integration for good: its tokens are revoked and wiped") c.add_argument("ref", metavar="NAME", help="the integration's name or id") add_yes(c, "the deletion") c.set_defaults(fn=cmd_integration_delete) ag = sub.add_parser("token", help="tokens: machine identities of the organisation, each with its own key, its own grants and an organisation role").add_subparsers(dest="sub", required=True) c = ag.add_parser("create", help="a new token; it holds exactly the grants given (none until granted otherwise) and the role given (member unless --role admin)") c.add_argument("--org", help=ORG_HELP); c.add_argument("--name", required=True) c.add_argument("--role", choices=("admin", "member"), help="organisation role of the token (default member): what it may do to the organisation, its people and its tokens; capped by your own role. Data access is its grants") c.add_argument("--grant", action="append", metavar="CATALOG:LEVEL", help=":, repeatable (a name is resolved here against lhbox catalog list); " "capped by your own level on each catalog") c.add_argument("--warehouse", action="append", metavar="CATALOG_ID", help=argparse.SUPPRESS) # deprecated: --grant :write c.add_argument("--send", action="append", metavar="SINK", help="a sink (id or name) the token may send batches to with its own key (`lhbox sink send` without a send key), " "repeatable; needs your write on the sink's catalog, and the token needs a --grant :read on it") c.set_defaults(fn=cmd_token_create) c = ag.add_parser("update", help="rename a token, replace its grants and/or change its role (admin, or the member who created it, within their own role)") add_token_positional(c) c.add_argument("--name", help="the new name") c.add_argument("--role", choices=("admin", "member"), help="new organisation role; capped by your own") c.add_argument("--grant", action="append", metavar="CATALOG:LEVEL", help=":, repeatable; the list REPLACES the current grants") c.add_argument("--send", action="append", metavar="SINK", help="a sink (id or name) the token may send to, repeatable; the list REPLACES the current one (--send '' clears it)") c.set_defaults(fn=cmd_token_update) c = ag.add_parser("list", help="the organisation's tokens; grants as [{catalog, level, warehouse_id}] in JSON, catalog:level on a terminal") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_token_list) c = ag.add_parser("revoke", help="revoke a token's key at once (admin, or the member who created it): lhbox token revoke ") add_token_positional(c) add_yes(c, "the revocation", takes_name=True) c.set_defaults(fn=cmd_token_revoke) c = sub.add_parser("whoami", help="who am I: identity, organisation, my level on each catalog, limits with headroom and whether " "each is enforced, the next step -- brief lines on a terminal, a brief JSON object when piped") c.add_argument("--full", action="store_true", help="the whole answer: every limit, project and organisation as tables on a terminal; " "piped or --json, GET /v1/usage as it comes plus the per-catalog levels (the default JSON is the brief object)") c.set_defaults(fn=cmd_whoami) c = sub.add_parser("doctor", help="check the whole path to a DuckDB session: API, credential, catalog (FAIL while it is still " "provisioning), recipe and level, a read through the catalog, write-policy (HEAD and a one-key " "list: the bucket accepts the identity, no object written), the DuckDB here, and whether a newer " "lhbox is published (WARN); PASS/FAIL/SKIP/WARN per line, exit 1 on any FAIL. Writes nothing " "unless --write-probe") add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP) c.add_argument("--write-probe", dest="write_probe", action="store_true", help="also write and delete a 0-byte %s in the table bucket as the recipe's identity: the one check that sees a " "store refusing writes (the store's error is quoted verbatim on FAIL)" % WRITE_PROBE_KEY) c.set_defaults(fn=cmd_doctor) c = sub.add_parser("bug", help="report a bug in LakehouseBox: opens the public tracker's bug form (github.com/lakehousebox/" "lakehousebox) filled in with this machine's lhbox, OS, Python and DuckDB versions; sends " "nothing itself. Piped: the link and the details as JSON, for an agent to show its person", description="Builds the bug form's URL; you review and submit it. The tracker is public: what you pass " "is scrubbed of key and secret shapes, and no organisation, catalog or home directory is " "added. A security vulnerability goes to a private report instead " "(%s/security/advisories/new)." % ISSUES_URL) c.add_argument("--title", help="one line: what is wrong") c.add_argument("--what", help="what happened: the error as printed (its `code` above all)") c.add_argument("--command", help="what you ran: the command, SQL or MCP tool call") c.add_argument("--no-open", dest="no_open", action="store_true", help="print the link, do not open a browser") c.set_defaults(fn=cmd_bug) for verb, fn, helptext in (("plan", cmd_plan, "say what `lhbox apply` would change to match lakehouse.yaml: the catalog, " "its migrations, POST prefixes, connections, scheduled SQL sinks (with " "each query's diff), descriptions; changes nothing"), ("apply", cmd_apply, "make the catalog match lakehouse.yaml: migrations first, then the " "rest; creates and updates, deletes only with --prune, publishes only " "with --publish, never a table or a row")): c = sub.add_parser(verb, help=helptext, description="lakehouse.yaml declares a catalog and what feeds it (PLAN 21; /docs/migrations/). " "Tables come from its migrations only. Changes are made through the same routes " "and checks as by hand: a sink's query is previewed before it is created or changed.") c.add_argument("-f", "--file", default="lakehouse.yaml", help="the file (default lakehouse.yaml)") if verb == "apply": c.add_argument("-m", "--message", help="why: kept with every change this run makes (lhbox history). Default: " "the subject of the last commit of the file's repository") c.add_argument("--prune", action="store_true", help="also delete the sinks, connections and POST prefixes the " "file no longer names (never a table or its rows)") c.add_argument("--publish", action="store_true", help="also make the catalog public (or private) as the file " "says") c.add_argument("--yes", action="store_true", help="confirm deletes and publishing without asking") c.set_defaults(fn=fn) c = sub.add_parser("migrate", help="apply a repository's numbered SQL migrations (sql/migrations/NNN_*.sql: CREATE TABLE, " "COMMENT ON) to a catalog, each once, in order; nothing that writes or drops", description="Each file runs once per catalog; the catalog records it with its checksum, and a file " "edited after it ran is refused (--repair records it as it is now). A table that exists is " "left as it is and its differences from the file are reported. `-- lhbox: " "format-version=3 partition=day(ts)` above a CREATE TABLE says what DuckDB DDL cannot.") add_catalog_flag(c) c.add_argument("--dir", default="sql/migrations", help="the folder of NNN_.sql files (default sql/migrations)") c.add_argument("--dry-run", dest="dry_run", action="store_true", help="say what would run; send nothing") c.add_argument("--repair", action="store_true", help="record edited files as they are now (what they declare already " "holds); runs nothing") c.set_defaults(fn=cmd_migrate) c = sub.add_parser("update", help="install the lhbox the site publishes (its install script) when this one is older; " "--check only says. lhbox also prints one stderr line a day when it is behind " "(silence: LHBOX_NO_VERSION_CHECK=1 or --no-version-check)") c.add_argument("--check", action="store_true", help="say which version is published, install nothing") c.add_argument("--site", metavar="URL", help="install from this site instead of %s (a self-hosted deployment's own): https, or http on this " "machine only; never taken from --url / LHBOX_URL, since its install script runs here" % SITE_URL) c.set_defaults(fn=cmd_update) c = sub.add_parser("logout", help="revoke the key this machine's login holds and remove it from the credentials file " "(--local: only remove it)") c.add_argument("--local", action="store_true", help="remove the saved login without revoking its key at the API") c.add_argument("--org", help="the organisation that holds the token (only needed when you belong to several)") c.set_defaults(fn=cmd_logout) pr = sub.add_parser("profile", help="the saved logins on this machine, one per account or organisation").add_subparsers(dest="sub", required=True) c = pr.add_parser("list", help="the profiles, the one in force marked") c.set_defaults(fn=cmd_profile_list) c = pr.add_parser("use", help="make a profile the default for every command (--profile and LHBOX_PROFILE still win)") c.add_argument("name") c.set_defaults(fn=cmd_profile_use) c = pr.add_parser("delete", help="remove a profile's saved login from this machine (logout --profile NAME revokes its key first)") c.add_argument("name") add_yes(c, "forgetting the saved login") c.set_defaults(fn=cmd_profile_delete) ev = sub.add_parser("env", help="the environment lhbox reads").add_subparsers(dest="sub", required=True) c = ev.add_parser("check", help="`set` or `missing` for LHBOX_API_KEY, LHBOX_URL, the saved login and the rest; never a value") c.set_defaults(fn=cmd_env_check) c = sub.add_parser("query", help="run one read statement (SELECT, DESCRIBE, SUMMARIZE, EXPLAIN) on the server over the " "catalogs you can read: 20 s, at most 2,000 rows and about 50,000 characters -- a quick " "look; lhbox duckdb for complete results", description="A quick-query and preview interface: one statement on LakehouseBox's shared engine, 20 " "seconds, and two independent caps on the answer, rows (--max-rows, default 200, at most " "2000) and characters (about 50,000 characters of JSON in all, whatever --max-rows says). " "An answer cut by either still exits 0 and says so: truncated: true, truncated_by: rows " "or characters, and local_compute, how to get the whole result (aggregate or filter in " "SQL, or the same SQL in your own DuckDB: lhbox duckdb --catalog , no caps). " "--require-complete makes a cut answer exit 2.") c.add_argument("sql", help="the SQL (DuckDB dialect), tables named catalog.namespace.table; '-' reads it from stdin") c.add_argument("--max-rows", type=int, dest="max_rows", help="rows to return (default 200, at most 2000); the character " "cap (about 50,000) can still cut a wide answer sooner") c.add_argument("--require-complete", action="store_true", dest="require_complete", help="exit 2 (code incomplete_result on stderr) when the answer was cut by either cap; the answer is " "still printed. Without it a cut answer exits 0") c.add_argument("--dry-run", action="store_true", dest="dry_run", help="run nothing: the tables it reads with their rows, files and bytes (an upper bound), and whether the cache would answer") c.add_argument("--engine", choices=("1.5", "2.0"), dest="engine", help="DuckDB engine version: 2.0 (DuckDB 2.0.0, default) or 1.5 (DuckDB 1.5.6, the fallback, for " "claimed accounts)") c.set_defaults(fn=cmd_query) c = sub.add_parser("usage", help="limits, current usage and headroom (which limits are enforced), one row per catalog -- a brief " "JSON object when piped, tables on a terminal; --catalog for one catalog's storage and traffic by day") add_catalog_flag(c, help="one catalog's view, day by day: stored bytes and objects, S3 requests and bytes in/out; " + CATALOG_HELP) c.add_argument("--days", type=int, help="length of the daily history, 1..30 (default 7)") c.add_argument("--full", action="store_true", help="piped or --json: GET /v1/usage as it comes (limits_detail, every project's " "warehouse_storage with history[]) instead of the brief object") c.set_defaults(fn=cmd_usage) c = sub.add_parser("history", help="what changed in your catalogs' configuration: every change to a sink, a connection, " "a catalog's settings, a table's schema or docs, with who, how and why", description="The object history. `lhbox history` lists the newest changes of the catalogs you read; " "`lhbox history ` those of one object (a sink's name or id, a table as " "namespace.table, a catalog's name); `--change ` shows one whole, with the object " "before and after. Say why you change something with --reason on the command that " "changes it.") c.add_argument("object", nargs="?", help="an object's name or id: a sink, a table (namespace.table), a connection") add_catalog_flag(c, help="one catalog, by name or id (default: every catalog you read)") c.add_argument("--type", help="one kind of object: sql_sink, send_sink, sql_connection, post_prefix, catalog_settings, " "agents_md, table, blob_index, migration") c.add_argument("--since", help="24h, 7d, 30m, or an ISO-8601 timestamp") c.add_argument("--operation", help="the changes of one operation (one `lhbox apply` run)") c.add_argument("--change", metavar="CHANGE_ID", help="one change, whole: the object before and after") c.add_argument("--limit", type=int, default=50, help="at most this many changes (max 500)") c.set_defaults(fn=cmd_history) c = sub.add_parser("restore", help="put a sink, a catalog's settings or an AGENTS.md back to a version from its history " "(lhbox history), or undo everything one `lhbox apply` run changed", description="`lhbox restore ` makes the object what that change made it; --undo makes it " "what it was before that change. `lhbox restore --operation ` undoes every change " "of one operation. Nothing is overwritten unseen: if the object changed after the " "version you looked at, the restore stops and names who changed it. The restore is " "itself a change in the history (op restore). Say why with --reason.") c.add_argument("change_id", nargs="?", help="the change whose version to put back (lhbox history shows the ids)") c.add_argument("--undo", action="store_true", help="put the object back to what it was BEFORE that change") c.add_argument("--operation", metavar="ID", help="undo every change of one operation (one lhbox apply run)") c.add_argument("--redo", action="store_true", help="with --operation: put back what the operation made, not what it replaced") c.add_argument("--by", metavar="ACTOR_ID", help="with --operation: whose changes to undo when several callers used the " "id (default: yours)") c.add_argument("--allow-empty", dest="allow_empty", action="store_true", help="a sink's query that previews 0 rows where its recent runs had rows is still put back") c.add_argument("--yes", action="store_true", help="do it without asking") c.set_defaults(fn=cmd_restore) c = sub.add_parser("audit", help="who did what: your events, or your organisation's (owner/admin)") c.add_argument("--org", help="org_id: the organisation's events (owners and admins) instead of only yours") c.add_argument("--since", help="24h, 7d, 30m, or an ISO-8601 timestamp") c.add_argument("--action", help="one action, e.g. credentials.vend, or a prefix like org.*") c.add_argument("--limit", type=int, default=100, help="at most this many events (max 1000)") c.set_defaults(fn=cmd_audit) ad = sub.add_parser("admin", help="install administration (a self-hosted install: status, first-run setup) and the operator's " "plans and limits; LHBOX_OPERATOR_KEY or, where named, --login with an install " "administrator's own password and code; never the agent key").add_subparsers(dest="sub", required=True) c = ad.add_parser("status", help="the install: release, security settings and where each is set, sign-in, SIEM export, " "backups, storage, administrators (read-only)") c.add_argument("--login", metavar="EMAIL", help="as this install administrator: password and authenticator code asked on the " "terminal, the session ended after the command (default: LHBOX_OPERATOR_KEY)") c.set_defaults(fn=cmd_admin_status) c = ad.add_parser("setup", help="first-run setup of a self-hosted install: the install administrator and the first " "organisation, with the one-time token `./al setup-link` printed on the host") c.add_argument("--token", required=True, help="the setup token (lhbsetup_...)") c.add_argument("--email", required=True); c.add_argument("--name", required=True, help="your name") c.add_argument("--org", required=True, help="the first organisation's name") c.add_argument("--handle", help="its handle (default: from the name)") g = c.add_mutually_exclusive_group() g.add_argument("--password-stdin", dest="password_stdin", action="store_true", help="read the password from standard input") g.add_argument("--no-password", dest="no_password", action="store_true", help="no password: you sign in with the install's identity provider (AL_OIDC_ISSUERS)") c.set_defaults(fn=cmd_admin_setup) login_help = ("as this install administrator: password and authenticator code asked on the terminal, the session ended " "after the command (default: LHBOX_OPERATOR_KEY)") c = ad.add_parser("plans", help="every plan by name with its limits and features") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_plans) ao = ad.add_parser("org", help="one organisation's plan and limits").add_subparsers(dest="sub2", required=True) c = ao.add_parser("limits", help="the organisation's plan, overrides, effective limits and features, and last changes") c.add_argument("org", help="org_id or handle") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_org_limits) c = ao.add_parser("set", help="put the organisation on a plan and/or override limits; a flag not passed leaves that limit as it is") c.add_argument("org", help="org_id or handle") c.add_argument("--plan", help="the plan name (lhbox admin plans)") c.add_argument("--storage-gb", dest="storage_gb", type=float, help="private storage limit in decimal GB (x 1000^3 bytes)") c.add_argument("--public-storage-gb", dest="public_storage_gb", type=float, help="public storage limit in decimal GB") c.add_argument("--objects", type=int, help="objects per catalog (a guideline today)") c.add_argument("--catalogs", type=int, help="catalogs per project") c.add_argument("--sql-sinks", dest="sql_sinks", type=int, help="scheduled SQL sinks of the organisation; 0 = not enabled " "(the default), N enables the feature with at most N sinks") c.add_argument("--sql-min-every", dest="sql_min_every", type=int, metavar="SECONDS", help="the shortest schedule (default 300)") c.add_argument("--sql-run-seconds", dest="sql_run_seconds", type=int, help="one run's wall time (default 60)") c.add_argument("--sql-requests-per-run", dest="sql_requests_per_run", type=int, help="HTTP requests per run (default 1000)") c.add_argument("--sql-download-mb-per-run", dest="sql_download_mb_per_run", type=int, help="MiB downloaded per run (default 1024)") c.add_argument("--projects", type=int, help="projects per account") c.add_argument("--clear", action="append", metavar="FIELD", help="remove one override by its API name (lhbox admin plans lists them, " "e.g. storage_bytes); repeatable") c.add_argument("--feature", action="append", metavar="NAME=VALUE", help="switch a plan feature or set any limit by its API name: on/off or a number, e.g. public_images=on " "(photos served from public folders) or device_sinks=20; repeatable (lhbox admin plans lists the names)") c.add_argument("--note", help="why (kept with the change in the audit log)") c.add_argument("--login", metavar="EMAIL", help=login_help) c.set_defaults(fn=cmd_admin_org_set) c = ao.add_parser("create", help="a new organisation and its first admin: an existing person at once, any other address " "by an admin invitation (its link printed once)") c.add_argument("handle", help="the organisation's handle (its address and the prefix of its storage names)") c.add_argument("--admin", required=True, metavar="EMAIL", help="the first admin's address") c.add_argument("--name", help="its display name (default: the handle)") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_org_create) c = ao.add_parser("list", help="every organisation, newest first: handle, members, catalogs, stored") c.add_argument("--q", help="search handle or name"); c.add_argument("--limit", type=int, default=100) c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_org_list) aoa = ao.add_parser("admin", help="an organisation's admins").add_subparsers(dest="sub3", required=True) c = aoa.add_parser("add", help="make an address an admin (a member is promoted, an existing person added, anyone else invited)") c.add_argument("org", help="org_id or handle"); c.add_argument("email") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_org_admin_add) c = aoa.add_parser("remove", help="an admin becomes a member (the last admin is refused); an open admin invitation is withdrawn") c.add_argument("org", help="org_id or handle"); c.add_argument("member", help="email or principal_id") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_org_admin_remove) ap_ = ad.add_parser("person", help="a person's access: suspend, reactivate, revoke every session and key").add_subparsers( dest="sub2", required=True) for action, text in (("suspend", "refuse their login and every credential of theirs and of their tokens, until reactivated"), ("reactivate", "lift a suspension (not one the organisation's directory made)"), ("revoke-all", "revoke every session, API key and token of the person, in every organisation " "(the account stays; not reversible)")): c = ap_.add_parser(action, help=text) c.add_argument("person", help="email or principal_id") if action == "suspend": c.add_argument("--reason", help="kept in the audit log") if action == "revoke-all": add_yes(c, "revoking every credential of the person") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_person, action=action) acl = ad.add_parser("client", help="approved OAuth/MCP clients: they connect with dynamic registration off").add_subparsers( dest="sub2", required=True) c = acl.add_parser("add", help="register a client (public by default; --confidential prints its secret once)") c.add_argument("--name", required=True) c.add_argument("--redirect-uri", dest="redirect_uri", action="append", required=True, metavar="URI", help="https, loopback http or a native app's scheme; repeatable") c.add_argument("--client-id", dest="client_id", help="the client's own fixed id (default: one is generated)") c.add_argument("--client-uri", dest="client_uri", help="its home page (https), shown on the consent page") c.add_argument("--confidential", action="store_true", help="a client with a secret (HTTP Basic or client_secret_post)") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_client_add) c = acl.add_parser("list", help="the clients install administrators registered, and whether dynamic registration is on") c.add_argument("--all", action="store_true", help="the self-registered (dynamic) clients too") c.add_argument("--login", metavar="EMAIL", help=login_help); c.set_defaults(fn=cmd_admin_client_list) for action, text in (("disable", "no new sign-in and no refresh (reversible)"), ("enable", "undo disable"), ("remove", "remove it and revoke every connection made through it")): c = acl.add_parser(action, help=text) c.add_argument("client_id") if action == "remove": add_yes(c, "removing the client") c.add_argument("--login", metavar="EMAIL", help=login_help) c.set_defaults(fn=cmd_admin_client_remove if action == "remove" else cmd_admin_client_toggle, action=action) an = ad.add_parser("news", help="the product-news mailing list: status, write an issue, test it, send it").add_subparsers( dest="sub2", required=True) c = an.add_parser("status", help="subscribers, withdrawals, whether sending is configured, the issues"); c.set_defaults(fn=cmd_admin_news_status) c = an.add_parser("create", help="a draft issue from a Markdown file") c.add_argument("--subject", required=True); c.add_argument("--file", required=True, help="Markdown file, or - for stdin") c.set_defaults(fn=cmd_admin_news_create) c = an.add_parser("show", help="one issue: state, delivery counts, text"); c.add_argument("issue"); c.set_defaults(fn=cmd_admin_news_show) c = an.add_parser("edit", help="change a draft's subject or text (needs a new test)") c.add_argument("issue"); c.add_argument("--subject"); c.add_argument("--file", help="Markdown file, or - for stdin") c.set_defaults(fn=cmd_admin_news_edit) c = an.add_parser("test", help="send the issue to one address, subject prefixed [test]") c.add_argument("issue"); c.add_argument("--to", required=True); c.set_defaults(fn=cmd_admin_news_test) c = an.add_parser("send", help="send the issue to every subscriber, once (needs a test after the last edit); on an issue " "already sending, resumes a send the relay paused") c.add_argument("issue") c.add_argument("--retry-failed", dest="retry_failed", action="store_true", help="also put the rows the relay refused for " "good back in line") c.set_defaults(fn=cmd_admin_news_send) pr = sub.add_parser("project", help="projects (placement is immutable)").add_subparsers( dest="sub", required=True) c = pr.add_parser("create"); c.add_argument("--name", required=True) c.add_argument("--provider", help="default: the deployment's own") c.add_argument("--region", help="default: the deployment's own placement") add_idem(c); c.set_defaults(fn=cmd_project_create) c = pr.add_parser("list"); c.set_defaults(fn=cmd_project_list) # `catalog` is the command group a person reads; `warehouse` (the API's name) is the same parser object # registered under a second name, kept out of the top-level help and of the generated docs cat_parser = sub.add_parser("catalog", help="catalogs: one Iceberg catalog per lakehouse, with its own storage and identity " "(the API names one by catalog_id, under /v1/catalogs)") sub._name_parser_map["warehouse"] = cat_parser wh = cat_parser.add_subparsers(dest="sub", required=True) c = wh.add_parser("create", help="a new catalog: `lhbox catalog create ` puts it in the organisation's default " "project; usually seconds, up to ~2 minutes on a busy host, progress on stderr", description="POST /v1/catalogs. `lhbox catalog create ` (lowercase letters, digits, _; a letter " "first). Usually done in a few seconds; on a busy host it can take up to two minutes: a line every " "~10 s says so; a timeout is exit 5 with the remedy to check `catalog list` " "first. Should the server answer 202 status: provisioning, the CLI polls until ready (--no-wait " "returns at once).") c.add_argument("name_arg", nargs="?", metavar="CATALOG", help="the catalog's name") c.add_argument("--name", help=argparse.SUPPRESS) # the pre-2026-09-21 spelling, kept as an alias c.add_argument("--project", help=PROJECT_HELP + " (default: the organisation's default project)") c.add_argument("--default-format-version", type=int, choices=(2, 3), default=None, metavar="{2,3}", help=FORMAT_DEFAULT_HELP + " (default 3; 2 for tables PyIceberg writes)") c.add_argument("--access", choices=tuple(GENERAL_ACCESS), default=None, help="general access: restricted (only the people and tokens given access read it) or organisation " "(every member of the organisation reads it, and so does anyone who joins). Default: the " "organisation's policy for new catalogs (`lhbox org policy`), restricted unless an admin changed it") c.add_argument("--no-wait", dest="no_wait", action="store_true", help="do not poll a 202 provisioning answer until ready") add_idem(c); c.set_defaults(fn=cmd_warehouse_create) c = wh.add_parser("list", help="every catalog you can see: name, id (warehouse_id in the API), your level, project, status and " "the format version its new tables get, side by side") c.add_argument("--project", help=PROJECT_HELP + " (default: every project you can see)") c.set_defaults(fn=cmd_warehouse_list) c = wh.add_parser("get", help="one catalog by name or id: the row of `catalog list` plus its bucket, storage figure, " "default format version and status (ready, or provisioning while its storage has not " "accepted a write yet)", description="GET /v1/catalogs/{id}. `lhbox catalog get `; without a name, your only catalog.") add_catalog_positional(c, hide_flag=True) c.set_defaults(fn=cmd_warehouse_get) c = wh.add_parser("measure", help="measure a catalog's storage now (bytes and objects of its two buckets) instead of " "waiting for the next reading (every 5 minutes); once a minute per catalog", description="POST /v1/catalogs/{id}/measure. `lhbox catalog measure `. Reads the " "store's own figure for the catalog's table bucket and blob bucket and stores it; GET /v1/usage " "and `catalog list` show it until the next reading (stale_after). Read level suffices.") add_catalog_positional(c, hide_flag=True) c.set_defaults(fn=cmd_warehouse_measure) c = wh.add_parser("update", help="change a catalog's settings: its general access (restricted, or everyone in the " "organisation; admin), the format version LakehouseBox gives its new tables " "(admin, or a write holder)", description="PATCH /v1/catalogs/{id}; `--access` is PUT /v1/catalogs/{id}/org-access. `lhbox catalog " "update --access restricted|organisation`: who reads the catalog without a grant of " "their own. restricted: only the people and tokens given access (the default of a new " "catalog); organisation: every member reads it. Making it restricted takes it from the " "members who read it only as members and replaces the key pairs they fetched (asked on a " "terminal; --yes otherwise). `lhbox catalog update --default-format-version 2|3` " "(the catalog is always named). " + FORMAT_DEFAULT_HELP + ". Tables an engine creates " "itself keep the version the engine chose; existing tables are unchanged. GET /v1/config/formats " "(no login) lists which engines write each version.") add_catalog_positional(c, default_rule=False, hide_flag=True) c.add_argument("--access", choices=tuple(GENERAL_ACCESS), default=None, help="general access: restricted (only the people and tokens given access read it) or organisation " "(every member of the organisation reads it); an admin, changed on its own") c.add_argument("--yes", dest="yes", action="store_true", help="with --access restricted: do not ask. The members who read the catalog only as members of the " "organisation lose it and the key pairs they fetched are replaced; required without a terminal") c.add_argument("--default-format-version", type=int, choices=(2, 3), default=None, metavar="{2,3}", help="3 (geometry/geography columns, deletion vectors; the default for new catalogs) or 2 (written by " "every engine, PyIceberg included)") c.add_argument("--snapshot-retention-days", default=None, metavar="N|default", help="keep every snapshot of the last N days (1-90; at most 500 per table) so tables can be read or " "rolled back to any point in them; `default` returns to 20 snapshots / 7 days, whichever is " "tighter (admin only; retained snapshots count as storage)") c.add_argument("--edge-reads", choices=("on", "off"), default=None, help="edge caching for this private catalog: its readers' lhbox duckdb sessions read through our " "European CDN (an admin; /docs/edge-caching/)") c.add_argument("--virtual-host", choices=("on", "off"), default=None, help="serve https://.s3. for this catalog (Snowflake needs it; an admin asking for " "its recipe turns it on). Its TLS certificate lists the bucket names in the public Certificate " "Transparency logs (admin only; off by default, public catalogs included)") c.set_defaults(fn=cmd_warehouse_update) c = wh.add_parser("rotate", help="replace the catalog's credentials (read/write and read-only): `lhbox catalog rotate `; " "the old keys and their tokens are refused at once, vended storage sessions run out within an hour; " "slow (identity writes at the store), progress on stderr") add_catalog_positional(c, default_rule=False, hide_flag=True) add_yes(c, "a rotation", takes_name=True) c.add_argument("--show-secrets", dest="show_secrets", action="store_true", help="print the two new secrets; without it they are ******** (fetch one later with " "`lhbox connect --show-secrets`)") c.set_defaults(fn=cmd_warehouse_rotate) c = wh.add_parser("grants", help="who holds read or write on a catalog, and how (admin, membership, creator, explicit): " "`lhbox catalog grants `") add_catalog_positional(c, hide_flag=True) c.set_defaults(fn=cmd_warehouse_grants) c = wh.add_parser("grant", help="grant read or write on a catalog to a member or a token (admin, or a write holder up to write): " "`lhbox catalog grant --principal --level read|write`") add_catalog_positional(c, default_rule=False, hide_flag=True) c.add_argument("--principal", required=True, help="principal_id of the member or token (lhbox org members / token list)") c.add_argument("--level", required=True, choices=("read", "write")) c.add_argument("--namespace", metavar="NS", help="grant only this namespace of the catalog, to a principal holding nothing on the catalog itself " "(an enterprise feature; admins only); it gets its own credentials, confined to the namespace") # one table of the catalog (table-level grants, platform/docs/table-grants.md): unlisted until sold (root CLAUDE.md, # rule 10) -- it works, it is not in --help nor in the published CLI reference c.add_argument("--table", metavar="NS.TABLE", help=argparse.SUPPRESS) c.add_argument("--all-catalogs", action="store_true", help="with --namespace on the system catalog (lhbox) only, where it is required: the schema is about " "every catalog of the organisation, so its reader sees rows about catalogs they do not hold. " "It does not grant several catalogs") c.set_defaults(fn=cmd_warehouse_grant) c = wh.add_parser("revoke", help="revoke a grant (admin, or whoever made it): `lhbox catalog revoke --principal `; " "revoking a member's membership read records level none") add_catalog_positional(c, default_rule=False, hide_flag=True) c.add_argument("--principal", required=True) c.add_argument("--namespace", metavar="NS", help="revoke the grant on this one namespace (the catalog-level grant stays as it is)") c.add_argument("--table", metavar="NS.TABLE", help=argparse.SUPPRESS) # table grants: unlisted, as above add_yes(c, "the revocation", takes_name=True) c.set_defaults(fn=cmd_warehouse_revoke) c = wh.add_parser("delete", help="delete a catalog (admin): `lhbox catalog delete --confirm ` (or --yes); it stays " "restorable for the service's grace period (`lhbox catalog restore`), then tables, buckets and " "identities are purged; --purge deletes for good at once") add_catalog_positional(c, default_rule=False, hide_flag=True) add_confirm(c, "name") c.add_argument("--purge", action="store_true", help="skip the grace period: purge tables, buckets and identities now, irreversibly (also ends the grace " "period of a catalog already deleted; name it with --confirm )") c.set_defaults(fn=cmd_warehouse_delete) c = wh.add_parser("restore", help="restore a catalog in its deletion grace period (admin): `lhbox catalog restore `; " "same tables and buckets, a new key pair if the old one was revoked, comes back private") add_catalog_positional(c, default_rule=False, hide_flag=True) c.set_defaults(fn=cmd_warehouse_restore) c = wh.add_parser("publish", help="make a catalog PUBLIC (admin, the name typed out): every data file and every retained " "metadata.json becomes readable by anyone without credentials, and anyone can attach it read-only by " "name (/), no account needed; its bytes count against the public allowance (5 GB; 50 GB once reviewed)", description="Puts one plain S3 bucket policy on the catalog's bucket (anyone may GET and LIST its objects, " "unsigned; writes and deletes stay refused). Public means the whole catalog: every table, " "every data file, every retained metadata.json including the table's history, and the list of " "object names. Readers with no account attach the whole catalog by name, read-only, " "through the public catalog: ATTACH '/' (TYPE iceberg, ENDPOINT , AUTHORIZATION_TYPE 'none'), its answers and files served from the CDN; " "`lhbox catalog public-url ` prints that line, and a table's metadata URL with --table. " "Any account also attaches it by name in lhbox duckdb (a shared public-reader key: catalog " "reads only, replaced at unpublish). The catalog's FILE bucket stays private " "unless --files / names one folder of it to publish too (GET, range requests and " "listing under that folder only). Undo with: lhbox catalog unpublish (tables and " "files). `lhbox catalog publish --confirm [--files public/]` (or --yes).") add_catalog_positional(c, default_rule=False, hide_flag=True) add_confirm(c, "name") files = c.add_mutually_exclusive_group() files.add_argument("--files", metavar="PREFIX", help="also publish ONE folder of the catalog's file bucket, e.g. public/ (ends in /): anyone may GET its " "data files (range requests included; photos only for organisations approved for it) and list " "the files under it at public_files_url; the rest of the file " "bucket stays private. Publishing again with another folder replaces it; without --files the " "published folder, if any, stays as it is") files.add_argument("--no-files", action="store_true", help="stop publishing the file bucket's folder; the catalog's tables stay public") c.set_defaults(fn=cmd_warehouse_publish) c = wh.add_parser("unpublish", help="make a public catalog private again (admin): `lhbox catalog unpublish `; " "anonymous reads are refused at once") add_catalog_positional(c, default_rule=False, hide_flag=True) add_confirm(c, "hidden") # reversible (publish again): accepted, not asked for c.set_defaults(fn=cmd_warehouse_unpublish) c = wh.add_parser("public-url", help="the public URL of a catalog and the no-credentials DuckDB recipe: `lhbox catalog " "public-url `; with --table, that table's current metadata URL (the thing to paste " "into iceberg_scan)") add_catalog_positional(c, hide_flag=True) c.add_argument("--table", metavar="NS.TABLE", help=".
: also print its current metadata_url and version_hint_url") c.set_defaults(fn=cmd_warehouse_public_url) up_parser = wh.add_parser("uploader", help="write-only credentials for the catalog's blob bucket: a relay, a camera, a " "field device or a partner dropping files under one prefix, never able to read, " "list (unless asked) or touch tables (https://lakehousebox.com/docs/uploaders/)") up = up_parser.add_subparsers(dest="sub2", required=True) c = up.add_parser("create", help="a new uploader: a key that can only upload under its prefix of the catalog's file bucket; " "the secret is shown once (--show-key) or written to a 0600 file (--save)", description="POST /v1/catalogs/{id}/uploaders. Write level. " "Without --save or --show-key the command stops before calling the API: no identity is " "created whose secret nobody received. The uploader cannot read what it uploads; consume " "the files from the catalog side with the catalog's own credential (lhbox connect). " "`lhbox catalog uploader create --name ...`.") add_catalog_positional(c, hide_flag=True) c.add_argument("--name", required=True, help="who uploads: relay, camera-north, partner-acme (a lowercase letter, then lowercase, digits, _ -)") c.add_argument("--prefix", default="", help="key prefix the credential is confined to, e.g. photos/2026/ (default: the whole blob bucket)") c.add_argument("--list", action="store_true", help="also allow ListBucket under the prefix (an s3:prefix condition: the device must " "list with ?prefix=); without it the uploader cannot list at all") c.add_argument("--expires-at", dest="expires_at", metavar="ISO8601", help="shown as the status 'expired' after that time; within the hour after it the key is removed and a drop-box " "login refused, as if revoked") c.add_argument("--protocols", metavar="LIST", help="also a drop-box login for devices that speak only FTP: a comma list of ftps, " "sftp, ftp (plain, unencrypted); the login and password are generated and shown once like the secret") c.add_argument("--save", metavar="FILE", help="write the pair, endpoint, bucket and prefix to FILE (mode 0600) and do not print the secret") c.add_argument("--show-key", dest="show_key", action="store_true", help="print the secret once (as well as saving it, with --save)") c.set_defaults(fn=cmd_uploader_create) c = up.add_parser("list", help="the catalog's uploaders without their secrets (never stored); --all includes revoked ones") add_catalog_positional(c, hide_flag=True) c.add_argument("--all", action="store_true", help="include revoked uploaders") c.set_defaults(fn=cmd_uploader_list) c = up.add_parser("revoke", help="revoke an uploader by id or name: its key is deleted at the store first and refused at once " "(revoke, then create, to replace a lost or leaked secret)") add_catalog_positional(c, hide_flag=True) c.add_argument("--uploader", required=True, help="the uploader_id or the name (lhbox catalog uploader list)") add_yes(c, "the revocation", takes_name=True) c.set_defaults(fn=cmd_uploader_revoke) lc_parser = wh.add_parser("lifecycle", help="expiry rules on the catalog's blob bucket: delete camera/ after 90 days, abort " "stale multipart uploads; never on tables (https://lakehousebox.com/docs/lifecycle/)") lc = lc_parser.add_subparsers(dest="sub2", required=True) c = lc.add_parser("set", help="add or replace ONE rule (by id; the default id is the prefix), keeping the others", description="PUT /v1/catalogs/{id}/lifecycle. Write level. Reads the current rules first and re-puts them " "with this one (the S3 API replaces the whole document); --replace-all keeps none. Objects are " "deleted at the store's next daily pass after they are due (up to 24 h late), permanently. " "Transitions do not exist here (no storage classes); --expire-days 0 is refused (the store " "would accept it and never fire it).") add_catalog_positional(c, hide_flag=True) c.add_argument("--prefix", default="", help="key prefix the rule applies to, e.g. camera/ (default: the whole blob bucket)") c.add_argument("--expire-days", dest="expire_days", type=int, metavar="N", help="delete objects N days (24 h each) after their last write; at least 1") c.add_argument("--expire-date", dest="expire_date", metavar="YYYY-MM-DD", help="delete every matching object at the first pass on or after this date (a past date: the next pass)") c.add_argument("--abort-multipart-days", dest="abort_multipart_days", type=int, metavar="N", help="abort multipart uploads not completed N days after they began") c.add_argument("--id", help="the rule's id (default: the prefix without slashes, or 'bucket'); a rule with the same id is replaced") c.add_argument("--disabled", action="store_true", help="store the rule disabled (kept, not evaluated)") c.add_argument("--replace-all", dest="replace_all", action="store_true", help="drop every other rule, this one alone remains") c.set_defaults(fn=cmd_lifecycle_set) c = lc.add_parser("get", help="the rules configured on the blob bucket, including any set with boto3") add_catalog_positional(c, hide_flag=True) c.add_argument("--xml", action="store_true", help="print the stored S3 LifecycleConfiguration document instead of the table") c.set_defaults(fn=cmd_lifecycle_get) c = lc.add_parser("clear", help="remove every lifecycle rule from the blob bucket") add_catalog_positional(c, hide_flag=True) add_yes(c, "removing every rule", takes_name=True) c.set_defaults(fn=cmd_lifecycle_clear) c = wh.add_parser("agents-md", help="the catalog's AGENTS.md: context for agents at the root of its file bucket (read, --set, --remove)", description="GET, PUT or DELETE /v1/catalogs/{id}/agents-md. The object AGENTS.md at the root of the catalog's " "file bucket; readable anonymously while the catalog is public. Reading needs read level; --set " "and --remove need write level. At most 64 KB of UTF-8; every write is audited.") add_catalog_positional(c, hide_flag=True) c.add_argument("--set", metavar="FILE", help="write FILE (or - for stdin) as the catalog's AGENTS.md") c.add_argument("--base-sha256", dest="base_sha256", metavar="SHA256", help="with --set: write only if the current AGENTS.md has this sha256 (none: only if there is none yet)") c.add_argument("--remove", action="store_true", help="delete the catalog's AGENTS.md") c.add_argument("--raw", action="store_true", help="print the text alone, no header") c.add_argument("--draft", action="store_true", help="print a draft AGENTS.md built from the catalog's tables (descriptions, columns and their docs, " "row counts, last updates), with a TODO where a person has to write; nothing is set: save it, " "edit it, then --set. Printed as text even when piped; --json wraps it") add_confirm(c, "hidden") c.set_defaults(fn=cmd_catalog_agents_md) fl_parser = sub.add_parser("file", help="the catalog's files (its file bucket, beside the tables): cp, sync, put, get, ls, " "rm, aws s3 style, with the catalog side written lhbox:/// -- no " "aws CLI or boto3 needed (https://lakehousebox.com/docs/files/)") fl = fl_parser.add_subparsers(dest="sub", required=True) file_catalog_help = CATALOG_HELP + CATALOG_DEFAULT_HELP + "; a lhbox:///… address names it too" def upload_flags(c): c.add_argument("--content-type", help="the media type (default: from the file's name; a published file is served " "with the type its name says either way)") c.add_argument("--cache-control", help="the file's Cache-Control, kept and passed to readers by the CDN of published " "files (default there: public, max-age=3600)") c.add_argument("--content-disposition", help='e.g. attachment; filename="report.csv"') c.add_argument("--content-language", help="e.g. en, or es-ES") c.add_argument("--meta", "--metadata", dest="meta", action="append", metavar="NAME=VALUE", help="custom metadata, sent as x-amz-meta-NAME: name=value, several as a=1,b=2 (aws's shorthand) " "or JSON {\"a\": \"1\"}; repeat the flag for more") c.add_argument("--part-size", type=int, metavar="MIB", help="files larger than this go up in parts of this size " "(MiB, at least 5; default 64)") c.add_argument("--parallel", type=int, default=FILE_PARALLEL_DEFAULT, metavar="N", help="parts uploaded at once (default %d)" % FILE_PARALLEL_DEFAULT) c.add_argument("--skip-refused", dest="skip_refused", action="store_true", help="upload what the catalog's files accept and list the rest as skipped (web pages, scripts, " "programs, and files over 100 kB of a type not on the list) and the platform's keys (AGENTS.md, " "_… at the root); without it such a file stops " "the upload before anything is sent") c = fl.add_parser("cp", help="copy files in or out, as aws s3 cp: `lhbox file cp ./tiles.pmtiles lhbox://garden/public/`, " "`lhbox file cp lhbox://garden/data/a.csv .`, `lhbox file cp ./exports lhbox://garden/exports/ " "--recursive`", description="Exactly one side is the catalog, written lhbox:/// (the " "catalog's name or id); the other is a local path. Up (local -> catalog) is `file put`: one " "file goes to the key, or under it when the key ends with / (or is empty); a directory's " "contents go under the prefix, relative paths kept, with or without --recursive (hidden " "files skipped). Down (catalog -> local) is `file get` for one key (DEST a file, a " "directory, or - for stdout); a key ending with /, or --recursive, downloads everything " "under it as a folder into the DEST directory. s3:// URLs are not taken: the bucket is the " "platform's name. --exclude/--include filter by path relative to the source.") c.add_argument("src", metavar="SRC", help="a local file or directory, or lhbox:///") c.add_argument("dst", metavar="DST", help="lhbox:///, or a local path") add_catalog_flag(c, help=file_catalog_help) c.add_argument("--recursive", action="store_true", help="a folder: download everything under the prefix (an upload of " "a directory is recursive either way)") _add_file_filters(c) upload_flags(c) c.add_argument("--skip-unchanged", action="store_true", help="skip files whose stored copy has the same size and ETag " "(what sync does)") c.add_argument("--dry-run", "--dryrun", dest="dry_run", action="store_true", help="list what would be copied and send nothing") c.add_argument("--progress", action="store_true", help="progress lines on stderr even when it is not a terminal") _add_aws_flags(c) c.add_argument("--no-edge", dest="no_edge", action="store_true", help="download from the storage even where the catalog has edge caching (a network that cannot reach the CDN)") c.set_defaults(fn=cmd_file_cp) c = fl.add_parser("sync", help="copy only what changed, as aws s3 sync: `lhbox file sync ./exports lhbox://garden/exports/` " "(or lhbox://garden/exports/ ./exports); never deletes", description="Recursive cp that skips every file whose other copy has the same size and ETag (its " "content: a second run sends nothing); any other file is copied over, so the source wins (a " "file edited on the destination side is replaced, whatever its age). Up: the directory's " "contents go under the prefix. " "Down: everything under the prefix into the directory, relative paths kept. A key ending " "with / or not, SRC/DST under lhbox:// is a folder. Nothing is ever deleted on either " "side (no --delete): lhbox file rm --recursive removes files from the catalog.") c.add_argument("src", metavar="SRC", help="a local directory, or lhbox:///") c.add_argument("dst", metavar="DST", help="lhbox:///, or a local directory") add_catalog_flag(c, help=file_catalog_help) _add_file_filters(c) upload_flags(c) c.add_argument("--dry-run", "--dryrun", dest="dry_run", action="store_true", help="list what would be copied and send nothing") c.add_argument("--progress", action="store_true", help="progress lines on stderr even when it is not a terminal") c.add_argument("--recursive", action="store_true", help=argparse.SUPPRESS) # sync is recursive; accepted c.set_defaults(skip_unchanged=True) _add_aws_flags(c) c.add_argument("--no-edge", dest="no_edge", action="store_true", help="download from the storage even where the catalog has edge caching (a network that cannot reach the CDN)") c.set_defaults(fn=cmd_file_sync) c = fl.add_parser("put", help="upload a file, or a directory recursively, to the catalog's files: `lhbox file put " "tiles.pmtiles public/ --cache-control \"public, max-age=86400\"` (the same as " "`lhbox file cp tiles.pmtiles lhbox:///public/`)", description="Uploads through URLs the API signs (POST /v1/catalogs/{id}/blobs/upload; a file over " "--part-size goes up in parts, in parallel, each retried on its own: POST " "…/blobs/multipart). Write level. KEY: the key for one file (KEY ending in / = KEY + the " "file's name; default: its name), or the prefix for a directory (default: the directory's " "name), under which relative paths are kept; hidden files are skipped. KEY may be " "lhbox:///. Prints JSON {uploaded, skipped, count, bytes, seconds} when " "piped. Keys starting with _ at the root and AGENTS.md are the platform's.") c.add_argument("sources", metavar="PATH", help="a local file or directory") c.add_argument("key_arg", nargs="?", metavar="KEY", help="the key (one file) or prefix (a directory) in the catalog's files") add_catalog_flag(c, help=file_catalog_help) upload_flags(c) c.add_argument("--skip-unchanged", action="store_true", help="skip files whose stored copy has the same size and ETag") c.add_argument("--recursive", action="store_true", help="accepted as in aws s3; a directory is uploaded recursively " "with or without it") _add_file_filters(c) c.add_argument("--dry-run", "--dryrun", dest="dry_run", action="store_true", help="list what would be uploaded and send nothing") c.add_argument("--progress", action="store_true", help="progress lines on stderr even when it is not a terminal") _add_aws_flags(c) c.set_defaults(fn=cmd_file_put) c = fl.add_parser("get", help="download one file: `lhbox file get data/a.csv [DEST]` (-o PATH works too; - for stdout)") c.add_argument("key", metavar="KEY", help="the file's key, or lhbox:///") c.add_argument("dest", nargs="?", metavar="DEST", help="where to write it (a directory keeps the name; - = stdout; " "default: the file's name here)") add_catalog_flag(c, help=file_catalog_help) c.add_argument("-o", "--output", metavar="PATH", help="the same as DEST") c.add_argument("--progress", action="store_true", help="progress lines on stderr even when it is not a terminal") c.add_argument("--no-edge", dest="no_edge", action="store_true", help="download from the storage even where the catalog has edge caching (a network that cannot reach the CDN)") _add_aws_flags(c) c.set_defaults(fn=cmd_file_get) c = fl.add_parser("ls", help="list the catalog's files: `lhbox file ls public/` or `lhbox file ls lhbox://garden/public/` " "(folders first; --recursive for every key)") c.add_argument("prefix", nargs="?", metavar="PREFIX", help="list under this prefix (end a folder with /); " "lhbox:/// works too") add_catalog_flag(c, help=file_catalog_help) c.add_argument("--recursive", action="store_true", help="every key under the prefix, no folders") _add_aws_flags(c, AWS_FLAGS_IGNORED + ("--human-readable", "--summarize")) c.set_defaults(fn=cmd_file_ls) c = fl.add_parser("rm", help="delete files: `lhbox file rm data/a.csv` or `lhbox file rm lhbox://garden/data/ --recursive` " "(asks only on a terminal)") c.add_argument("keys", nargs="+", metavar="KEY", help="the keys (or prefixes, with --recursive); lhbox:/// " "works too") add_catalog_flag(c, help=file_catalog_help) c.add_argument("--recursive", action="store_true", help="delete every file under each KEY taken as a folder") _add_file_filters(c) c.add_argument("--dry-run", "--dryrun", dest="dry_run", action="store_true", help="list what would be deleted and delete nothing") c.add_argument("--parallel", type=int, default=FILE_PARALLEL_DEFAULT, metavar="N", help="deletes sent at once (default %d); on a refusal those already sent finish, and the error lists " "what was deleted and what was not" % FILE_PARALLEL_DEFAULT) c.add_argument("--yes", dest="yes", action="store_true", help="do not ask: the deletion cannot be undone. Asked [y/N] only when a person is at a terminal; a " "script or an agent (no terminal) deletes without it, as aws s3 rm does") c.add_argument("--confirm", dest="confirm", nargs="?", const=True, metavar="NAME", help=argparse.SUPPRESS) _add_aws_flags(c) c.set_defaults(fn=cmd_file_rm) ns = sub.add_parser("namespace", help="namespaces (created on demand by table create)" ).add_subparsers(dest="sub", required=True) c = ns.add_parser("list"); add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP) c.set_defaults(fn=cmd_namespace_list) c = ns.add_parser("delete", help="drop one EMPTY namespace: `lhbox namespace delete --catalog `; asks unless " "--yes; a namespace with tables is refused (drop them first with `table delete`), a " "public catalog wants --force") c.add_argument("namespace_ref", metavar="NAMESPACE") add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP) add_drop_flags(c) c.set_defaults(fn=cmd_namespace_delete) tb = sub.add_parser("table", help="tables").add_subparsers(dest="sub", required=True) c = tb.add_parser("list", help="every table in a catalog, or in one namespace") add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP) c.add_argument("--namespace", help="restrict to one namespace") c.set_defaults(fn=cmd_table_list) c = tb.add_parser("get", help="schema, real format-version, snapshot and row count: `lhbox table get ..
` " "(or .
--catalog )") add_table_positional(c, nargs="?") add_catalog_flag(c) c.set_defaults(fn=cmd_table_get) c = tb.add_parser("delete", help="drop one table and its data files: `lhbox table delete .
--catalog `; " "asks unless --yes; a public catalog wants --force; cannot be undone") add_table_positional(c, nargs=None, hidden_flags=False) add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP) add_drop_flags(c) c.set_defaults(fn=cmd_table_delete) c = tb.add_parser("create", help="a new table from --column specs or a schema file: `lhbox table create ..
" "--column id:long:required …` (or .
--catalog )") add_table_positional(c, nargs="?") add_catalog_flag(c) c.add_argument("--column", action="append", help="name:type[:required][:identifier], repeatable") c.add_argument("--schema-file", help="a full Iceberg schema as JSON, e.g. " + SCHEMA_EXAMPLE) c.add_argument("--format-version", type=int, default=None, choices=(2, 3), metavar="{2,3}", help="2 or 3; default: the catalog's default_format_version (3 unless changed with lhbox catalog " "update). 3 holds geometry/geography columns; PyIceberg writes only 2; GET /v1/config/formats " "says which engines write each. The version actually used is printed on stderr.") c.add_argument("--partition", action="append", metavar="TRANSFORM(COLUMN)", help="partition the table, repeatable: day(ts), hour(ts), month(ts), year(ts), a column name (identity), " "bucket[16](id), truncate[4](code). A sink feeds a format-version 3 table partitioned by time " "(day(
`; " "the secret key and session token are ******** unless --show-secrets") add_table_positional(c, nargs="?", name_flag="--table") add_catalog_flag(c) c.add_argument("--show-secrets", dest="show_secrets", action="store_true", help="print the secret key and the session token (for boto3 or the aws CLI); without it they are ********") c.add_argument("--expires", type=int, metavar="SECONDS", help="a shorter lifetime, 60-3600 seconds (default: the service's, 3600)") c.set_defaults(fn=cmd_credentials) c = sub.add_parser("connect", help="a paste-ready recipe for your own engine, carrying the identity that matches your level " "(read holders get the read-only one; snowflake does unless --write); with one catalog visible no " "--catalog is needed; for duckdb the DuckDB on this machine is checked against 1.5.5") add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP + PUBLIC_CATALOG_HELP + " (--engine duckdb only)") c.add_argument("--engine", default="duckdb", choices=("duckdb", "pyiceberg", "spark", "snowflake", "trino", "polars", "clickhouse"), help="trino prints a catalog properties file; polars a PyIceberg-backed Python snippet; clickhouse " "reads only (icebergS3, one table at a time); snowflake reads unless --write") lvl = c.add_mutually_exclusive_group() lvl.add_argument("--write", action="store_true", help="the WRITING recipe, asked for explicitly (you must hold write on the catalog). For snowflake: the " "read/write key pair in an external volume with ALLOW_WRITES = TRUE plus a catalog-linked database, " "so Snowflake creates and writes Iceberg tables here; the pair is static and stays in Snowflake") lvl.add_argument("--readonly", action="store_true", help="the catalog's READ-ONLY recipe whatever level you hold (identity t--ro: the catalog refuses its " "commits, the store its PUT/DELETE) -- with --readonly --show-secrets, the recipe to send a colleague " "who should read your catalog, or to paste under 'Add catalog' in the account page's explorer (the " "secret is masked otherwise)") c.add_argument("--no-version-check", dest="no_version_check", action="store_true", default=argparse.SUPPRESS, help="do not run `duckdb --version` / `python3 -c 'import duckdb'` (writes need DuckDB 1.5.5 or newer: " "older versions write manifests the catalog's maintenance cannot read)") c.add_argument("--show-secrets", dest="show_secrets", action="store_true", help="print the catalog credential's secret; without it the secret is ******** wherever the recipe " "repeats it (the key id is shown) and a DuckDB recipe starts with an error() naming this flag. Pipe " "it rather than show it: `lhbox connect --show-secrets --human | duckdb`; `lhbox duckdb` attaches " "without showing it; the sample code reads LHBOX__CLIENT_ID / _CLIENT_SECRET") # namespace and table grants (unlisted, platform/docs/table-grants.md): a scoped member's catalog token instead of its # pair; a service account's vended-only recipe gets it without asking c.add_argument("--catalog-token", dest="catalog_token", action="store_true", help=argparse.SUPPRESS) c.add_argument("--edge", action="store_true", help=argparse.SUPPRESS) # Edge reads (docs/edge-reads.md): unlisted until it is offered c.set_defaults(fn=cmd_connect) c = sub.add_parser("duckdb", help="open the `duckdb` shell already attached to the catalog (the recipe goes in through a " "0600 init file, deleted at once; the credential is never on screen or in argv); " "--persist instead writes DuckDB persistent secrets so a bare ATTACH works in any session", description="Without --persist: runs the duckdb binary with -init pointing at a private 0600 file holding " "the connect recipe (secrets and ATTACH), removes the file a second later, and hands you the " "shell with the catalog attached under its alias. Arguments after -- go to duckdb. With " "--persist: runs CREATE OR REPLACE PERSISTENT SECRET lhbox_ (TYPE ICEBERG) and " "lhboxs3_ (TYPE S3, scoped to the catalog's bucket) in DuckDB, so any later " "session -- the shell or python -- needs only the printed ATTACH line. Trade-off: the persistent " "secrets keep the catalog credential on disk in DuckDB's secret directory (~/.duckdb/stored_secrets, " "0600), readable by any DuckDB this user runs; revoke with lhbox catalog rotate (for a catalog lhbox " "new made, once a person has claimed it) or DROP PERSISTENT SECRET.") add_catalog_flag(c, help=CATALOG_HELP + CATALOG_DEFAULT_HELP + PUBLIC_CATALOG_HELP + " (not with --persist)") c.add_argument("--edge", action="store_true", help=argparse.SUPPRESS) # Edge reads (docs/edge-reads.md): unlisted until it is offered c.add_argument("--no-edge", dest="no_edge", action="store_true", help="read from the storage even where the catalog has edge caching on (a network that reaches the " "storage but not the CDN)") c.add_argument("--credential-process", dest="credential_process", action="store_true", help=argparse.SUPPRESS) # with --edge: DuckDB's credential_process (edge_credential_config) c.add_argument("--files", dest="edge_files", action="store_true", help=argparse.SUPPRESS) # with --credential-process: the files bucket's edge credential c.add_argument("--persist", action="store_true", help="write persistent DuckDB secrets and print the ATTACH line instead of opening a shell") c.add_argument("--python", metavar="PATH", help="with --persist: the interpreter whose duckdb module writes the secrets (env LHBOX_PYTHON)") c.add_argument("--no-version-check", dest="no_version_check", action="store_true", default=argparse.SUPPRESS, help="do not warn about a duckdb older than 1.5.5") c.add_argument("duckdb_args", nargs=argparse.REMAINDER, metavar="-- DUCKDB_ARGS", help="passed to the duckdb binary, e.g. -- -readonly or -- mydb.duckdb") c.set_defaults(fn=cmd_duckdb) sk_parser = sub.add_parser("sink", help="ingest sinks: one HTTP intake per table for a device, a webhook or an agent without an " "engine; JSON arrays in, Iceberg rows out on a rolling policy (https://lakehousebox.com/docs/ingest/)") sk = sk_parser.add_subparsers(dest="sub", required=True) c = sk.add_parser("create", help="a new sink on an existing table (unpartitioned, or a format-version 3 table partitioned by " "time); the send key is shown once (--show-key) or written to a 0600 file (--save)", description="POST /v1/sinks. Write level on the catalog. Nothing is committed until the first roll, which adds the " "optional __ingest_ts column and the metadata-retention properties. Several appending sinks (no key) may share a table; a keyed one is alone on it. Without " "--save or --show-key the command stops before calling the API: no sink is created whose key nobody " "received. `lhbox sink create --catalog --table .
--name --save sink.json`.") add_catalog_positional(c, hide_positional=True) c.add_argument("--table", required=True, metavar="NS.TABLE", help="the table the sink feeds, .
; it must exist (lhbox table create)") c.add_argument("--name", required=True, help="the sink's name (the catalog rule: lowercase letter, then lowercase, digits, _)") c.add_argument("--roll-seconds", dest="roll_seconds", type=int, metavar="N", help="commit what is waiting every N seconds (default 300, floor 60); a roll is a commit, 300-900 suits a small producer") c.add_argument("--roll-bytes", dest="roll_bytes", type=int, metavar="N", help="also roll when N bytes wait (32-64 MiB; default 64 MiB)") c.add_argument("--inactivity-seconds", dest="inactivity_seconds", type=int, metavar="N", help="also roll when the sink has been quiet for N seconds") c.add_argument("--key", metavar="COL[,COL]", help="replace the rows that share these columns at each roll instead of appending " "them again (a format-version 2 table; e.g. --key observation_id): the latest row per key wins") c.add_argument("--save", metavar="FILE", help="write the send key, the send URL and the sink id to FILE (mode 0600) and do not print the key") c.add_argument("--show-key", dest="show_key", action="store_true", help="print the send key once (as well as saving it, with --save)") _add_device_flags(c) g = c.add_argument_group("scheduled SQL: the sink runs a DuckDB query on a schedule; no send key") g.add_argument("--sql", metavar="SQL", help="one DuckDB SELECT reading public http(s) URLs, inline, @file or @- (stdin)") g.add_argument("--every", metavar="DURATION", help="how often it runs: 1m, 20m, 1h, 300 (at least the plan's minimum, 1 min)") g.add_argument("--offset", metavar="DURATION", help="where in the interval it runs (every 20m offset 2m: :02, :22, :42)") g.add_argument("--create-table", dest="create_table", action="store_true", help="create the table from the query's columns " "when it does not exist, in --format-version (default: the catalog's default format version)") g.add_argument("--format-version", dest="format_version", type=int, choices=(2, 3), help="with --create-table: the new table's Iceberg format version; 3 for a geometry column or --partition, " "2 for --key. A query that does not fit it is refused before the table is made") g.add_argument("--partition", action="append", metavar="TRANSFORM(COLUMN)", help="with --create-table and format version 3: partition the new table by time, repeatable: day(ts), " "hour(ts), month(ts), year(ts) of a date or timestamp column") g.add_argument("--paused", action="store_true", help="create it paused (run it by hand with lhbox sink run)") g.add_argument("--engine", choices=("2.0", "1.5"), help="the DuckDB the query runs on: 2.0 (DuckDB 2.0.0, the default) or 1.5 " "(DuckDB 1.5.6); a sink keeps its engine until you change it, whatever the default becomes") g.add_argument("--mode", choices=("append", "replace"), help="what each run does to the table: append its rows (the " "default) or replace every row with them, in one snapshot per run (a format-version 2 table; time travel " "reads the versions the snapshot retention keeps). Fixed at creation") g.add_argument("--min-rows", dest="min_rows", type=int, metavar="N", help="with --mode replace: a run with fewer than N rows " "(default 1) fails and leaves the table as it is, so an empty source never empties it") g.add_argument("--replace-existing", dest="replace_existing", action="store_true", help="with --mode replace on a table that already holds rows: replace them at the first run") c.set_defaults(fn=cmd_sink_create) c = sk.add_parser("list", help="the sinks of every catalog you can see (or of one), with what is waiting and the last roll; never a key") add_catalog_positional(c, default_rule=False, hide_positional=True) c.add_argument("--all", action="store_true", help="include deleted sinks") c.set_defaults(fn=cmd_sink_list) c = sk.add_parser("get", help="one sink by id or name: state, roll policy, lag, last roll, rejects, totals") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.set_defaults(fn=cmd_sink_get) c = sk.add_parser("delete", help="delete a sink: its send key is refused from now on; batches still waiting are discarded " "(--force when there are any); the table is untouched") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--force", "--discard-pending", dest="force", action="store_true", help="delete even if batches are waiting for a roll (they are discarded)") add_yes(c, "the deletion") c.set_defaults(fn=cmd_sink_delete) c = sk.add_parser("send", help="POST one batch (a JSON array of objects in a file, or - for stdin) to a sink with its send key, " "or with your own key when it holds the sink's send grant", description="The send route, POST /v1/sinks/{id}: the key from --send-key-file (what `sink create --save` wrote), " "--send-key or LHBOX_SEND_KEY; without one, this machine's own key (a token given the sink with " "`lhbox token create --send`, or write on its catalog); the batch id from --batch-id or a fresh UUID. The same batch id " "again answers duplicate without storing twice. 202 accepted; 400 not an array; 413 over 16 MiB.") c.add_argument("sink", nargs="?", metavar="SINK", help="the sink_id (omit it when --send-key-file names one; a name works with your own key)") c.add_argument("file", metavar="FILE", help="a file holding a JSON array of objects, or - for stdin") c.add_argument("--send-key-file", dest="send_key_file", metavar="FILE", help="the file `sink create --save` wrote") c.add_argument("--send-key", dest="send_key", help="the send key itself (prefer --send-key-file or LHBOX_SEND_KEY)") c.add_argument("--batch-id", dest="batch_id", metavar="ID", help="the Idempotency-Key: 1-128 chars of A-Z a-z 0-9 . _ : - (default: a UUID)") c.set_defaults(fn=cmd_sink_send) c = sk.add_parser("device-token", help="give a sink a device route (a new URL; the old one is refused at once), or --revoke it", description="POST /v1/sinks/{id}/device-token: the URL a device that sets no header posts to. " "Shown once: --save FILE (0600) or --show-key. Counts against the plan's " "device_sinks when the sink had no route.") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--save", metavar="FILE", help="write the device URL and token to FILE (mode 0600)") c.add_argument("--show-key", dest="show_key", action="store_true", help="print the device URL once") c.add_argument("--revoke", action="store_true", help="remove the device route instead (DELETE)") c.set_defaults(fn=cmd_sink_device_token) c = sk.add_parser("mapping", help="show a sink's mapping, or set it (--preset / --mapping FILE) or remove it (--clear)", description="GET /v1/sinks/{id}?include_mapping=true, or PATCH /v1/sinks/{id} {mapping}. A mapping turns what a " "device sends into the table's rows at each roll: rename, drop, constants, a timestamp, and melt " "(one wide record into many long rows with unit conversions). Validated against the table.") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--preset", metavar="NAME", help="a mapping shipped with the platform: ecowitt, ispindel, ttn (The Things Stack webhooks), sensor-community") c.add_argument("--param", action="append", metavar="NAME=VALUE", help="a preset's parameter, e.g. WS=ws-01 (repeatable)") c.add_argument("--mapping", metavar="FILE", help="a mapping document (JSON)") c.add_argument("--clear", action="store_true", help="remove the mapping") c.set_defaults(fn=cmd_sink_mapping) c = sk.add_parser("test", help="dry-run a device body through a sink (the pinned secret, the strip list, the mapping) with your " "own key; nothing is stored", description="POST /v1/sinks/{id}/test. The content type follows the file's extension (.csv, .ndjson, .json) " "and defaults to form-urlencoded (what an Ecowitt gateway posts); --content-type overrides it.") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("file", metavar="FILE", help="a captured body, or - for stdin") c.add_argument("--content-type", dest="content_type", metavar="TYPE", help="the body's media type") c.add_argument("--limit", type=int, default=20, help="rows to print (default 20)") c.set_defaults(fn=cmd_sink_test) c = sk.add_parser("preview", help="run a scheduled-SQL query once, now, and write nothing: rows, columns and their Iceberg " "types, and whether they fit a table", description="POST /v1/sql/preview. The query runs on LakehouseBox's executor: public http(s) URLs only " "(read_json, read_csv, read_parquet, read_text, FROM 'https://...'), one SELECT. Errors name " "the column, the host or the budget, with a remedy.") add_catalog_positional(c, hide_positional=True) # --catalog, the positional silent (convention 2) c.add_argument("--sql", required=True, metavar="SQL", help="the SELECT, inline, @file or @- (stdin)") c.add_argument("--table", metavar="NS.TABLE", help="also check that the rows fit this table") c.add_argument("--limit", type=int, default=20, help="rows to print (default 20); the preview itself carries at most 50 " "rows and 50,000 characters per value, and says when it cut (truncated)") c.add_argument("--engine", choices=("2.0", "1.5"), help="the DuckDB to preview on: 2.0 (DuckDB 2.0.0, the default) or 1.5 " "(DuckDB 1.5.6)") c.add_argument("--format-version", dest="format_version", type=int, choices=(2, 3), help="without --table: check the query against the format version --create-table would use (default: the " "catalog's default); a geometry under 2 is listed as a problem") c.set_defaults(fn=cmd_sink_preview) c = sk.add_parser("run", help="run a SQL sink's query now, outside its schedule (a paused sink too)") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--wait", action="store_true", help="wait until the run is committed, empty or failed") c.add_argument("--timeout", type=int, default=300, help="seconds --wait waits (default 300)") c.set_defaults(fn=cmd_sink_run) c = sk.add_parser("runs", help="a SQL sink's runs, newest first: state, rows, requests, bytes, time, errors") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--limit", type=int, default=20, help="runs to show (default 20, at most 500)") c.set_defaults(fn=cmd_sink_runs) c = sk.add_parser("pause", help="stop a SQL sink's schedule (lhbox sink run still runs it by hand)") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.set_defaults(fn=cmd_sink_pause) c = sk.add_parser("resume", help="restart a paused SQL sink's schedule") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.set_defaults(fn=cmd_sink_resume) cn_parser = sk.add_parser("connection", help="credentials a scheduled-SQL query sends to an authenticated source " "(bearer, header, basic, query parameters): write-only, bound to a URL prefix", description="A connection is a named credential of one catalog, sent only to URLs that start with " "its https:// prefix; the SQL names the URL, never the credential. Values come from " "@FILE, @- (stdin) or an environment variable (--value-env), never inline, and no command shows them " "again. A person can also add one on the account page (the catalog's Sinks tab).") cn = cn_parser.add_subparsers(dest="conn_sub", required=True) c = cn.add_parser("create", help="a new connection: NAME, --url-prefix, one of --bearer / --header NAME / --basic, and " "--value @FILE, --value-env VAR or a hidden prompt; or --param NAME=SOURCE (query)", description="POST /v1/sql/connections. --basic takes user:password as its value. --param (kind " "query) appends the value to the URL's query string under the prefix.") c.add_argument("name", metavar="NAME", help="the connection's name (lower case letters, digits, _)") add_catalog_flag(c) c.add_argument("--url-prefix", dest="url_prefix", metavar="URL", help="https://host/path/ : the credential is sent only to URLs that start with it (ends in /)") c.add_argument("--integration", metavar="WEB_KEY", help="use the organisation's web key of this name (lhbox integration " "list; the one hosted agents send): its host, header and key, no copy, rotated in one place") c.add_argument("--bearer", action="store_true", help="send Authorization: Bearer ") c.add_argument("--header", metavar="HEADER", help="send the value in this header, e.g. X-API-Key") c.add_argument("--basic", action="store_true", help="send Authorization: Basic, the value being user:password") c.add_argument("--kind", choices=("bearer", "header", "basic", "query"), help="the kind, as an alternative to " "--bearer / --header NAME / --basic / --param") c.add_argument("--param", action="append", metavar="NAME=SOURCE", help="kind query (repeatable): append ?NAME=value " "to URLs under the prefix (http_get, http_post); SOURCE is @FILE, @- (stdin) or env:VAR, never the " "value; a bare NAME (one parameter) takes --value / --value-env / the prompt") c.add_argument("--value", metavar="@FILE", help="the credential: @FILE or @- (stdin); never inline") c.add_argument("--value-env", dest="value_env", metavar="VAR", help="read the credential from this environment variable " "(an agent that holds the key never writes it to a file); with neither, a terminal asks, hidden") c.set_defaults(fn=cmd_sink_connection_create) c = cn.add_parser("list", help="a catalog's connections (never their values)") add_catalog_flag(c) c.set_defaults(fn=cmd_sink_connection_list) c = cn.add_parser("replace", help="replace a connection's value (a rotated key)") c.add_argument("name", metavar="NAME", help="the connection's name") add_catalog_flag(c) c.add_argument("--value", metavar="@FILE", help="the new credential: @FILE or @- (stdin)") c.add_argument("--value-env", dest="value_env", metavar="VAR", help="read it from this environment variable") c.add_argument("--header", metavar="HEADER", help="a new header name (kind header only)") c.add_argument("--param", action="append", metavar="NAME=SOURCE", help="kind query: the parameters to replace, as " "at create (@FILE, @- or env:VAR); the others are kept") c.add_argument("--replace-all", dest="replace_all", action="store_true", help="kind query: the --param given are the " "whole set (the others are removed)") c.set_defaults(fn=cmd_sink_connection_replace) c = cn.add_parser("delete", help="delete a connection; SQL sinks whose query names its prefix are paused") c.add_argument("name", metavar="NAME", help="the connection's name") add_catalog_flag(c) add_yes(c, "deleting a connection") c.set_defaults(fn=cmd_sink_connection_delete) pp_parser = sk.add_parser("post-prefix", help="the URL prefixes a catalog's scheduled SQL may POST to (http_post); " "every other POST is refused", description="A scheduled query sends a request body (http_post: a form, a small JSON " "document) only to URLs under a prefix declared here. The egress proxy refuses " "any other POST, counts each in the run's request budget and records its host.") pp = pp_parser.add_subparsers(dest="post_sub", required=True) c = pp.add_parser("add", help="allow POST under an https:// prefix (ends in /)") c.add_argument("url_prefix", metavar="URL", help="https://host/path/ : POST is allowed to URLs that start with it") add_catalog_flag(c) c.set_defaults(fn=cmd_sink_post_prefix_add) c = pp.add_parser("list", help="a catalog's POST prefixes") add_catalog_flag(c) c.set_defaults(fn=cmd_sink_post_prefix_list) c = pp.add_parser("remove", help="stop allowing POST under a prefix") c.add_argument("url_prefix", metavar="URL", help="the prefix, as listed") add_catalog_flag(c) c.set_defaults(fn=cmd_sink_post_prefix_remove) c = sk.add_parser("dedupe", help="keep only the latest row per key in a keyed sink's whole table, once (rows stored " "before the key was set keep their duplicates otherwise)") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--wait", action="store_true", help="wait until the roller has done it, and print what it removed") c.add_argument("--timeout", type=int, default=1800, metavar="SECONDS", help="how long --wait waits (default 1800)") add_yes(c, "a dedupe removes the older rows of every key") c.set_defaults(fn=cmd_sink_dedupe) c = sk.add_parser("update", help="change a SQL sink's query or schedule (a new query is previewed against the table first), " "or any sink's key") c.add_argument("sink", metavar="SINK", help="the sink_id or the name") c.add_argument("--sql", metavar="SQL", help="the new SELECT, inline, @file or @- (stdin)") c.add_argument("--every", metavar="DURATION", help="the new interval") c.add_argument("--offset", metavar="DURATION", help="the new offset") c.add_argument("--engine", choices=("2.0", "1.5"), help="move the sink to this DuckDB: 2.0 (DuckDB 2.0.0) or 1.5 (DuckDB " "1.5.6); its query is previewed on it against the table first") c.add_argument("--min-rows", dest="min_rows", type=int, metavar="N", help="a replace sink's guard: a run with fewer than N " "rows fails and leaves the table as it is") c.add_argument("--force", action="store_true", help="accept a new query or engine whose preview returns 0 rows although " "the sink's recent runs had rows (refused otherwise: preview_empty)") k = c.add_mutually_exclusive_group() k.add_argument("--key", metavar="COL[,COL]", help="from the next roll, replace the rows that share these columns instead of " "appending them again (a format-version 2 table)") k.add_argument("--no-key", dest="no_key", action="store_true", help="drop the key: each roll appends again") c.set_defaults(fn=cmd_sink_update) ix_parser = sub.add_parser("index", help="blob index rules: every file uploaded under a prefix of a catalog's blob bucket " "becomes a row of a table (https://lakehousebox.com/docs/ingest/)") ix = ix_parser.add_subparsers(dest="sub", required=True) c = ix.add_parser("create", help="a new index rule on an existing table", description="POST /v1/indexes. Extractors, a JSON list (inline or @file) from: \"basic\" (bucket, object_key, " "filename, size_bytes, etag, content_type, last_modified, indexed_at, uploader), \"image\" (width, " "height, exif_taken_at), {\"type\": \"filename_time\", \"column\": …, \"pattern\": \"(\\\\d{14})\", " "\"format\": \"%%Y%%m%%d%%H%%M%%S\", \"tz\": \"Europe/Madrid\", \"fallback\": \"last_modified\"}, " "{\"type\": \"path_parts\", \"pattern\": \"^camera/(?P[^/]+)/\"}, " "{\"type\": \"constant\", \"values\": {…}}.") add_catalog_positional(c, hide_positional=True) c.add_argument("--name", required=True, help="the rule's name (lowercase letter, then lowercase, digits, _)") c.add_argument("--prefix", default="", help="the prefix of the blob bucket to watch, e.g. camera/ (default: all of it)") c.add_argument("--table", required=True, metavar="NS.TABLE", help="the table the rows go to; it must exist") c.add_argument("--extractors", required=True, metavar="JSON", help="the extractor list, inline JSON or @file") c.add_argument("--rename", action="append", metavar="EXTRACTED=COLUMN", help="store an extracted column under the table's name (repeatable)") c.add_argument("--poll-seconds", dest="poll_seconds", type=int, metavar="N", help="how often the prefix is listed (default 60, floor 30)") c.add_argument("--ordered-keys", dest="ordered_keys", action="store_true", help="the keys sort by time (dated folders such as camera/2026/11/06/): each poll lists from the newest " "folder indexed on, not the whole prefix; a file uploaded into an older folder is then never indexed") c.add_argument("--roll-seconds", dest="roll_seconds", type=int, metavar="N", help="commit the found files every N seconds (default 300, floor 60)") c.add_argument("--inactivity-seconds", dest="inactivity_seconds", type=int, metavar="N", help="also commit once nothing new was found for N seconds") c.set_defaults(fn=cmd_index_create) c = ix.add_parser("list", help="the index rules of every catalog you can see (or of one)") add_catalog_positional(c, default_rule=False, hide_positional=True) c.set_defaults(fn=cmd_index_list) c = ix.add_parser("get", help="one index rule by id or name: its last poll, what it indexed, its lag") c.add_argument("index", metavar="INDEX", help="the index_id or the name") c.set_defaults(fn=cmd_index_get) c = ix.add_parser("delete", help="stop indexing (the table, its rows and the files stay)") c.add_argument("index", metavar="INDEX", help="the index_id or the name") add_yes(c, "the deletion") c.set_defaults(fn=cmd_index_delete) cn = sub.add_parser("connection", help="connections: a credential for another system (a bucket, an Azure container, an " "Iceberg catalog, a Portolan catalog) and where it is; attach one as a connected catalog", description="A connection is your organisation's credential for another system and where that " "system is: today an S3-compatible bucket and folder with a key pair that can only " "read, a public bucket, or an Azure storage container (Blob or ADLS Gen2) and folder " "with a Microsoft Entra service principal that can only read, another Iceberg REST " "catalog (and the store its files are in), another organisation's public " "LakehouseBox catalog, or a Google BigQuery project (read as a service account " "LakehouseBox makes for the connection, which you grant). Its maker owns it and it is private until shared (lhbox " "connection share); its secret is sealed and never shown again. When its owner leaves " "the organisation it stops until an admin takes it over. Attach it with lhbox source " "attach.").add_subparsers(dest="sub", required=True) c = cn.add_parser("create", help="store a connection (yours, private until shared); the secret from a file, stdin or the environment") c.add_argument("name", help="the connection's name: lower case letters, digits and _") c.add_argument("--type", default="s3", choices=["s3", "azure_blob", "iceberg_rest", "lakehousebox", "portolan", "bigquery"], help="the kind of system (default s3); GET /v1/source-types describes each") c.add_argument("--endpoint", help="s3 and iceberg_rest: the store's host name (for iceberg_rest, where the tables' " "files are), e.g. s3.eu-central-1.amazonaws.com") c.add_argument("--bucket", help="s3 and iceberg_rest: the bucket") c.add_argument("--catalog-uri", dest="catalog_uri", help="iceberg_rest: the catalog's REST address (https), " "e.g. https://catalog.example.com/api/catalog") c.add_argument("--warehouse", help="iceberg_rest: the warehouse the catalog serves (a LakehouseBox catalog: its " "bucket)") c.add_argument("--auth", choices=["oauth2", "bearer", "none"], help="iceberg_rest: oauth2 (--client-id and its " "secret, the default), bearer (a token) or none (a public catalog)") c.add_argument("--token-path", dest="token_path", help="iceberg_rest, oauth2: where the catalog mints tokens, a path " "on its host (default /v1/oauth/tokens)") c.add_argument("--scope", help="iceberg_rest, oauth2: the scope, when the catalog wants one") c.add_argument("--catalog-secret", dest="catalog_secret", help="iceberg_rest: the OAuth2 client secret or the token: " "@FILE, or @- for stdin (never the secret itself)") c.add_argument("--catalog-secret-env", dest="catalog_secret_env", metavar="VAR", help="iceberg_rest: the client secret or token from an environment variable") c.add_argument("--namespace", action="append", help="iceberg_rest and lakehousebox: a namespace read (with what is " "under it); repeat, or separate with commas. None: every namespace") c.add_argument("--catalog", help="lakehousebox: another organisation's public catalog, /") c.add_argument("--catalog-url", dest="catalog_url", help="portolan: the catalog's root, https://host/bucket/folder/catalog.json (path style); " "public unless a key is given") c.add_argument("--data-url", dest="data_url", help="portolan: where its GeoParquet files are, when not under the " "catalog's folder, https://host/bucket/folder/") c.add_argument("--project", help="bigquery: the Google Cloud project id that holds the datasets") c.add_argument("--billing-project", dest="billing_project", help="bigquery: the project the reads are billed to " "(default --project)") c.add_argument("--dataset", action="append", help="bigquery: a dataset read; repeat, or separate with commas. None: " "every dataset its service account is granted") c.add_argument("--prefix", help="a folder inside the bucket or container: only keys under it are read") c.add_argument("--account", help="azure_blob: the storage account's name") c.add_argument("--container", help="azure_blob: the container (an ADLS Gen2 file system)") c.add_argument("--endpoint-suffix", dest="endpoint_suffix", help="azure_blob: the cloud's storage suffix " "(default core.windows.net)") c.add_argument("--tenant-id", dest="tenant_id", help="azure_blob: the Entra tenant (directory) id") c.add_argument("--client-id", dest="client_id", help="azure_blob: the service principal's application (client) id; " "iceberg_rest: the OAuth2 client's id; " "its client secret is --value or --value-env") c.add_argument("--region", help="default us-east-1") c.add_argument("--url-style", dest="url_style", choices=["path", "vhost"], help="default path") c.add_argument("--anonymous", action="store_true", help="a public bucket (e.g. Overture Maps): no key, the files are read with unsigned requests") def add_key_pair(p): p.add_argument("--access-key-id", dest="access_key_id", help="the key's id") p.add_argument("--access-key-id-env", dest="access_key_id_env", metavar="VAR", help="the key's id from an environment variable") p.add_argument("--value", help="the secret access key (an Azure connection: the client secret): @FILE, or @- for " "stdin (never the secret itself)") p.add_argument("--value-env", dest="value_env", metavar="VAR", help="the secret access key (or client secret) from " "an environment variable") p.add_argument("--org", help=ORG_HELP) add_key_pair(c); c.set_defaults(fn=cmd_connection_create) c = cn.add_parser("list", help="the connections you may use (an admin: all), with owner, state and sources") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_connection_list) c = cn.add_parser("show", help="one connection; never its secret") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_connection_show) c = cn.add_parser("rotate", help="replace a connection's key pair, or an Azure one's client secret, or an Iceberg " "catalog's secret and storage key together (its owner or an admin)") def add_new_secret(p): p.add_argument("name"); add_key_pair(p) p.add_argument("--catalog-secret", dest="catalog_secret", help="iceberg_rest: the new client secret or token: " "@FILE or @-") p.add_argument("--catalog-secret-env", dest="catalog_secret_env", metavar="VAR", help="iceberg_rest: the same, " "from an environment variable") add_new_secret(c); c.set_defaults(fn=cmd_connection_rotate) for verb, fn, what in (("share", cmd_connection_share, "let others attach sources from it"), ("unshare", cmd_connection_unshare, "stop letting them")): c = cn.add_parser(verb, help="%s (its owner or an admin); never shares its key" % what) c.add_argument("name") c.add_argument("--everyone", action="store_true", help="every member of the organisation") c.add_argument("--principal", help="one person or token, by id (lhbox org members, lhbox token list)") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=fn) c = cn.add_parser("take-over", help="make a connection yours with a key of your own, as rotate takes it (an Azure " "one's client secret, an Iceberg catalog's secret and storage key together; " "admin): how a connection whose owner left works again") add_new_secret(c); c.set_defaults(fn=cmd_connection_take_over) c = cn.add_parser("transfer", help="give a connection to another person or token of the organisation (its owner or an admin)") c.add_argument("name"); c.add_argument("--to", required=True, help="the new owner's id") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_connection_transfer) c = cn.add_parser("delete", help="delete a connection and its stored key pair (its owner or an admin); detach its sources first") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP) add_yes(c, "the deletion"); c.set_defaults(fn=cmd_connection_delete) so = sub.add_parser("source", help="connected catalogs: a connection attached under a name, read like a catalog where " "the data lives and never written (docs: /docs/connected-catalogs/)", description="A source is a connection attached under a name that SQL addresses beside your " "catalogs (name.schema.table). It is read-only. An admin attaches it; it is " "Restricted until opened to the organisation or granted.").add_subparsers( dest="sub", required=True) c = so.add_parser("attach", help="attach a connection as a source (admin)") c.add_argument("name", help="how SQL will name it: lower case letters, digits and _; not a catalog's name") c.add_argument("--connection", required=True, help="the connection's name (lhbox connection list)") c.add_argument("--everyone", action="store_true", help="every member of the organisation reads it (default: Restricted)") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_source_attach) c = so.add_parser("list", help="the sources you can read") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_source_list) c = so.add_parser("show", help="one source") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_source_show) c = so.add_parser("tables", help="a source's tables, each with the name SQL gives it") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_source_tables) c = so.add_parser("refresh", help="look at a source's files again and replace the list of its tables (admin)") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_source_refresh) c = so.add_parser("detach", help="detach a source: its grants go, its connection stays (admin)") c.add_argument("name"); c.add_argument("--org", help=ORG_HELP) add_yes(c, "detaching it"); c.set_defaults(fn=cmd_source_detach) c = so.add_parser("access", help="a source's general access: every member, or Restricted (admin)") c.add_argument("name") c.add_argument("access", choices=["everyone", "restricted"], help="everyone: every member of the organisation reads it; restricted: only admins and those granted it") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=cmd_source_access) for verb, fn, text in (("grant", cmd_source_grant, "give a member, a token or an agent the read of a source (admin)"), ("revoke", cmd_source_revoke, "take it back (admin)")): c = so.add_parser(verb, help=text) c.add_argument("name"); c.add_argument("--principal", required=True, help="the member's, token's or agent's id") c.add_argument("--org", help=ORG_HELP); c.set_defaults(fn=fn) mc = sub.add_parser("mcp", help="the MCP server for Claude Desktop, Claude Code and other hosts: install its " "configuration with the saved key, or run it").add_subparsers(dest="sub", required=True) mcp_source_help = ("developers: what uvx runs the local server from, normally a checkout's platform/mcp directory " "(default: the checkout this CLI runs from; the package lakehousebox-mcp is not published). " "Checked first: a source that cannot start the server is refused and nothing is written") c = mc.add_parser("install", help="write the mcpServers entry into a host's configuration; the key comes from " "LHBOX_API_KEY or the credentials file and is never printed nor put on a command line", description="Claude Code (default): adds the remote server {\"type\": \"http\", \"url\": " "\"https://mcp.lakehousebox.com/mcp\", \"headersHelper\": \" --url " "--profile mcp headers\"} with `claude mcp add-json` when `claude` is on PATH, " "else prints the entry and the command to run. The entry holds no key: Claude Code runs " "the helper when it connects, which reads LHBOX_API_KEY from Claude Code's environment, " "else the saved login, so a key given only with --api-key is refused. Claude Desktop: " "its config file takes only local " "servers, so the hosted server is a custom connector added in the app (Settings > " "Connectors > Add custom connector, signed in with OAuth); this prints those steps and " "writes nothing. --transport stdio (developers: a checkout's platform/mcp against a " "local stack) writes a local server instead, only when uv is installed and SOURCE " "resolves, else nothing is written: for Claude Code {\"command\": \"\", " "\"args\": [\"--url\", API, \"--profile\", PROFILE, \"mcp\", \"run\", \"--from\", " "SOURCE]} (no key in it); for Claude Desktop {\"command\": \"uvx\", \"args\": " "[\"--from\", SOURCE, \"lakehousebox-mcp\"], \"env\": {LHBOX_URL, LHBOX_API_KEY}}, " "merged into its claude_desktop_config.json (other servers kept) after a " ".bak- copy, both written 0600. The key comes from " "the credentials file (or --api-key / LHBOX_API_KEY); the five tools only read, so a " "token's key with read grants confines the server to those catalogs (and to public ones) (docs/mcp.md).") c.add_argument("--client", default="claude-code", choices=("claude-code", "claude-desktop"), help="which host's configuration to write (default: claude-code)") c.add_argument("--transport", choices=("http", "stdio"), help="http (default): the hosted server, nothing runs locally; stdio: a local server started with uvx " "from a checkout, for developers") c.add_argument("--mcp-url", help="the remote server (default: mcp./mcp next to the API's api.)") c.add_argument("--url", default=argparse.SUPPRESS, help="API base URL the server will talk to and whose saved key is used (default: the global --url / " "LHBOX_URL, i.e. %s)" % DEFAULT_URL) c.add_argument("--from", dest="source", metavar="SOURCE", help=mcp_source_help) c.add_argument("--name", default=MCP_SERVER_NAME, help="the server's name in the host (default: lhbox)") c.add_argument("--scope", default="user", choices=("local", "user", "project"), help="Claude Code only: user (default; every project on this machine), local (this project, this " "machine), or project (.mcp.json, shared through version control: it holds no key, but names " "this machine's lhbox)") c.add_argument("--print", action="store_true", help="print the mcpServers snippet instead of writing anything (for another host's configuration; " "a Claude Desktop entry's key is MASKED: put the real one in from the credentials file)") c.set_defaults(fn=cmd_mcp_install) c = mc.add_parser("headers", help="for programs: print {\"Authorization\": \"Bearer \"} (LHBOX_API_KEY, else the " "saved login), the headersHelper Claude Code runs for the entry `mcp install` " "writes; refused on a terminal without --show-key") c.add_argument("--url", default=argparse.SUPPRESS, help="API base URL whose saved key is used (default: the global --url / LHBOX_URL, i.e. %s)" % DEFAULT_URL) c.add_argument("--show-key", action="store_true", help="print it on a terminal too") c.set_defaults(fn=cmd_mcp_headers) c = mc.add_parser("run", help="start the MCP server over stdio with the saved key in its environment (for a host " "configured by hand: command lhbox, args mcp run); until the package is on PyPI it " "runs from a checkout (--from /platform/mcp): most hosts want `lhbox mcp " "install`, the hosted server, with nothing to run here") c.add_argument("--url", default=argparse.SUPPRESS, help="API base URL (default: the global --url / LHBOX_URL, i.e. %s)" % DEFAULT_URL) c.add_argument("--from", dest="source", metavar="SOURCE", help=mcp_source_help) c.add_argument("server_args", nargs=argparse.REMAINDER, metavar="-- SERVER_ARGS", help="passed to the server, e.g. -- --list-tools") c.set_defaults(fn=cmd_mcp_run) # the usage line lists the command groups a person should type; the hidden alias stays out of it sub.metavar = "{" + ",".join(n for n in sub.choices if n not in ("warehouse",) + UNLISTED_COMMANDS) + "}" # commands not offered yet stay out of the listing entirely (help=SUPPRESS printed `==SUPPRESS==` there) sub._choices_actions = [a for a in sub._choices_actions if a.dest not in UNLISTED_COMMANDS] _accept_globals_everywhere(p) return p def _url_from_words(words): """--url's value from the raw command line, for a usage error answered before the parser has run.""" found = None for i, w in enumerate(words): if w == "--": break flag, eq, value = w.partition("=") if len(flag) >= 4 and "--url".startswith(flag): # --ur is argparse's abbreviation; the last one wins found = value if eq else (words[i + 1] if i + 1 < len(words) else found) return found def run(argv=None): _install_user_agent() words = list(sys.argv[1:] if argv is None else argv) # a usage error asks the site of the API on the command line, never the default's (high review of #1512, 2) _CURRENT_URL[0] = _url_from_words(words) or DEFAULT_URL _VCHECK.update(off="--no-version-check" in words, said=False, command=None) # the mode a usage error is answered in, before the parser has run; then the parsed flags decide (_want_json) _OUTPUT_JSON[0] = "--json" in words or ("--human" not in words and not sys.stdout.isatty()) try: args = _parse_command_line(argv, words) if not hasattr(args, "idempotency_key"): args.idempotency_key = None _OUTPUT_JSON[0] = _want_json(args) _PROFILE[0] = getattr(args, "profile", None) _CURRENT_URL[0] = getattr(args, "url", None) or DEFAULT_URL _VCHECK["command"] = getattr(args.fn, "__name__", None) try: args.fn(args) except SystemExit as done: if done.code in (0, None): version_notice(args) unclaimed_notice(args) elif not _OUTPUT_JSON[0] and not _VCHECK["said"] and _newer_published(fetch=False): # a failure is when an old lhbox matters most (JSON: cli_outdated in the envelope); from the cache only, # and once: an envelope that said it already is not repeated (high review of #1512, 8) version_notice(args) raise version_notice(args) unclaimed_notice(args) finally: _OUTPUT_JSON[0] = None _PROFILE[0] = None def main(argv=None): """Entry point for both `python3 lhbox` and the pip console script (pyproject.toml).""" try: run(argv) except SystemExit: raise except KeyboardInterrupt: die("interrupted", EXIT_ERROR) except (TimeoutError, socket.timeout): # a timeout that escaped the request seams is still not a bug: the retry code and the "look first" remedy _die_timeout("request", "(see the command)", 0) except BrokenPipeError: # the reader of stdout went away (`lhbox table list | head -1`): nothing left to say, and nobody to say it to try: os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno()) except OSError: pass sys.exit(EXIT_ERROR) except _LOST_ANSWER as exc: # the same for a connection lost after a request that escaped them: never "a bug in lhbox, re-run" _die_lost_or_bad_url("request", "(see the command)", exc) except CredentialsUnreadable as exc: # a command that would write the credentials file back found it unreadable (#2573): nothing was written die_json("credentials_unreadable", str(exc.strerror), EXIT_ERROR, credentials_file=CRED_FILE_SHOWN, remedy="%s, then run the command again" % exc.remedy()) except Exception as exc: # noqa: BLE001 - deliberate backstop # The last line of defence. A traceback on stderr is unparseable for a JSON consumer and # prints our own absolute source paths at it; whatever went wrong, the caller gets an object. die_json("unexpected_cli_error", "The CLI hit an unexpected %s: %s" % (type(exc).__name__, exc), EXIT_ERROR, remedy="This is a bug in lhbox, not in your command. Re-run with the same " "arguments to confirm, then report it.") if __name__ == "__main__": main()