Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/docs/runtime-contract.md
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
runtime-contract.md · 61.0 KB · 1431 lines

Runtime Contract

This document records the public contract that DBBASIC Object Server code should preserve while the implementation is extracted from the working prototype.

The goal is compatibility. New public code should not create a parallel runtime shape that breaks existing DBBASIC objects, DBBASIC Scroll, or the current dbbasic_object_core import path without an explicit migration plan.

Package Boundary

The existing runtime package is:

from dbbasic_object_core.runtime.object_runtime import ObjectRuntime

For now, dbbasic_object_core is the compatibility target for the core runtime. If a future dbbasic_object_server package is added, it should start as a thin server or command-line layer around dbbasic_object_core, not as a replacement runtime namespace.

Object Source Root

New object source should live under:

objects/

The object source root can be overridden with:

DBBASIC_OBJECTS_DIR=/path/to/objects

Public code should not use the old prototype directory name as a default.

Object ID Resolution

The daemon-facing object ID rules are:

  • category_name resolves to objects/category/name.py
  • u_{user_id}_{name} resolves to objects/users/{user_id}/{name}.py
  • trigger objects live under objects/triggers/

Public code should use object_namespace.py for object source lookup rather than reimplementing these rules in each server, daemon, or tool surface.

Current trigger object names:

  • scheduler
  • queue
  • events

Runtime Interface

The daemon expects a runtime object with:

runtime.load_object(path, object_id=None)

path is a Path or string pointing to an object source file. object_id is optional when the ID can be derived from the file name, and required when executing a resolved target object by ID.

The returned object must expose:

obj.logger
obj.state_manager
obj.execute(method, payload)

Loaded object modules receive _logger, _state_manager (get, set, increment, get_all, reload), _files, _runtime, and _schedule / _unschedule (see "Self-Scheduled Methods" below). A loaded object also exposes obj.file_manager. See "Runtime Helpers" in object-authoring.md for _files and _runtime; they are injected by PythonObject, so they behave identically in-process, in warm pool workers and in spawned children. User-namespace objects get proxies with the same names and return shapes instead; see "User Object Isolation" below.

User Object Isolation

Any object whose id starts u_<digits>_ (or whose source lives under users/<uid>/) is user code. User code never runs in the server process, the admin warm pool (DBBASIC_WORKER_POOL_SIZE) or the spawn-per-request path. Every one of those entry points -- HTTP, execute_object, the daemon, change dispatch, hooks, _runtime.load_object from a system object -- hands it to object_sandbox, and PythonObject itself refuses a user object as a last line, so a call site that forgets to route fails closed. Admin, system and package objects are untouched: same paths, same speed.

Two layers, because neither is enough alone:

  1. A separate OS user. Workers run as dbbasic-sandbox, a user that owns

no file and is in no group, started by a tiny root launcher. Landlock has no right for metadata, so before this layer a customer's object could os.chmod another customer's object to mode 0 (breaking it), os.utime it, and os.stat its size, owner and mtime -- the worker was the server's uid, which owns everything. As another uid it gets EPERM/EACCES, and it cannot signal the server either.

  1. The wall (below): rlimits, a scrubbed environment and Landlock, which

stop reading files, writing anywhere, executing programs and TCP.

The launcher (uid separation)

object_sandbox_launcher.py is the only code that runs as root, and it does one job (its docstring is the full argument):

  • It listens on /run/dbbasic-sandbox/launcher.sock (directory

root:dbbasic 0750, socket 0660), and answers only a peer whose SO_PEERCRED uid is the server's. Anyone else is logged and dropped.

  • A request is at most 4 KiB of length-prefixed JSON with known fields only

(v, op, env; env keys from the same allow-list as the scrubbed environment) and exactly two pipe fds attached with SCM_RIGHTS: the read end the worker uses as stdin, then the write end it uses as stdout. The server keeps the other ends, so the protocol below is unchanged. Anything else is refused and logged.

  • A fork server (see "Warm parents") is started the same way with

"channel": "socket" and exactly one fd, a connected AF_UNIX stream socket, which becomes its stdin and stdout; it needs a channel that can carry the per-call pipe fds it hands its children. A launcher too old to accept this simply means no warm parents: calls take spares.

  • It starts only the fixed entry point `<python> -I -B <object_sandbox.py>

--worker, both paths fixed on its own command line, in a new session. Before exec the child enters a fresh network namespace when the launcher has CAP_SYS_ADMIN, sets PR_SET_NO_NEW_PRIVS, drops to the sandbox user (setgroups([]), setresgid, setresuid) and proves it cannot get back (setuid(0)` fails, all ids match, no groups, no capabilities).

  • The connection is the worker's lifetime: when the server closes it (or

dies), the launcher kills the worker's process group, reaps it, then kills every process still in the worker's session (each through a pidfd, its session re-checked first, so a reused pid is never hit), waits for them and reaps them. It is a child subreaper, so a sandbox process whose parent died comes back to it rather than becoming a zombie under the container's PID 1. The server cannot signal another uid, so killing is the launcher's job.

  • A worker that ends by itself while its connection is open is reported on

that connection: one message, {"exited": true, "status": N} (the exit status, or minus the signal number), sent the moment it ends (a pidfd wakes the launcher). The server uses it only for the warning described under "Warm parents". A launcher that does not send it leaves the status unknown.

  • Root never runs anything the server can edit: deployments run a

root-owned copy of the launcher with the root-owned interpreter (python -I -S). The worker script and its interpreter may be the server's: they run as the sandbox user, which has less than the server already has.

The server keeps its private paths closed to other users: the data directory, every object root, a separate DBBASIC_BACKUPS_DIR and DBBASIC_ADMIN_TOKEN_FILE must have no "other" permission bits. Before every user-object run (and at startup) the server sets mode 0700 (0600 for a file) on any of them it owns that is open, and refuses user objects naming the path when it cannot. The installer and the Docker entrypoint set 0700 up front. The code directory stays readable: the worker must read object_sandbox.py, and the code is public.

Network namespace. With CAP_SYS_ADMIN (a bare VM; the systemd unit grants it) every worker (a spare or a warm parent, whose children share it) gets its own empty network namespace: no interface but a down loopback, so no TCP, UDP or abstract UNIX socket reaches anything, whatever the Landlock ABI. Docker's default capabilities lack it; the layer is then skipped and the status says so (--cap-add SYS_ADMIN would enable it, but grants the whole container far more than this layer needs, so it is not recommended by default). The systemd unit also starts the launcher with PrivateNetwork=true and RestrictAddressFamilies=AF_UNIX, which its workers inherit.

The wall

Each user-object request runs in a fresh process that serves that one request and is then killed: either a pre-started spare worker (python -I -B object_sandbox.py --worker, started by the launcher as above) or a child forked for that call by the user's warm parent (next section). A process that held user code is never reused, not even for the same user. Before any user code is read a spare worker, in this order:

  1. Starts with a scrubbed environment: PATH, LANG, LC_*, TZ (and the

interpreter's PYTHONHASHSEED/PYTHONDONTWRITEBYTECODE, ignored under -I). No DBBASIC_*, no tokens, no provider keys.

  1. Points fds 0/1/2 at /dev/null and keeps the protocol on private pipe

fds, so print() cannot corrupt the stream or write to the server log.

  1. Sets rlimits: RLIMIT_CPU, RLIMIT_AS (memory), RLIMIT_FSIZE=0,

RLIMIT_NOFILE (small), RLIMIT_CORE=0, RLIMIT_NPROC=0. NPROC=0 makes fork/clone fail for a non-root uid (the kernel compares the uid's process count, always >= 1, with the limit), which is why the worker refuses to boot as root. Threads count as processes, so user code cannot start threads either.

  1. Applies Landlock (landlock_create_ruleset/add_rule/restrict_self

via ctypes, after PR_SET_NO_NEW_PRIVS). The ruleset handles every filesystem, network and scope right the kernel accepts -- discovered by asking the kernel bit by bit, so a newer kernel's new right is denied without a code change -- and grants only READ_FILE/READ_DIR beneath the interpreter's own sys.path directories (stdlib, lib-dynload, site-packages) and /usr/share/zoneinfo, minus anything overlapping the repo, data, objects, packages or working directory (an editable install puts the repo on sys.path; it is dropped). Execute is denied everywhere; TCP bind and connect are denied on every port; on ABI >= 6 abstract UNIX sockets and signals cannot leave the domain. A worker that finds itself running as the server's own uid refuses to boot below ABI 6.

The parent reads the object's source and sends it over the pipe, so the sandbox never needs the objects directory. Stdlib modules whose C extension links a system library (hashlib, bz2, lzma, uuid, ...) are imported before the wall; other pure-Python stdlib imports work normally afterwards.

Warm parents

Booting a worker costs about 45 ms of CPU (interpreter start, imports, rlimits, Landlock), so a busy server's spares could not keep up and calls waited for one. A user who called recently therefore has a fork server: a worker booted exactly as above, as the sandbox user and behind the same wall, that never runs user code. Each call of that user is one child it forks.

Warm parents need Landlock ABI >= 6 by default. A warm parent lives for many calls and runs as the shared sandbox uid. Only from ABI 6 does Landlock scope signals, so that a call cannot signal any process outside its own domain; below it one user's code could SIGKILL another user's warm parent (sending that user to the spare path for 60 seconds) or SIGSTOP it (their next call waits the 2-second control timeout first) -- targeted interference with another customer, which spares, living for one call, do not invite. So DBBASIC_USER_CODE_WARM_PARENTS=auto (the default) turns warm parents on only at ABI >= 6. Ubuntu 24.04's HWE kernels (6.12 and later, 6.14 at the time of writing) qualify; its stock 6.8 kernel (ABI 4) does not, and there every call takes a spare as before. DBBASIC_USER_CODE_WARM_PARENTS=on opts in below ABI 6 anyway: calls are as fast, at the cost just described (no data becomes reachable, and ptrace stays blocked). off never uses them. The startup banner, object_sandbox.py --status and GET /admin/status (warm_parents.status) say which applies and why.

  • Never shared between users. One fork server per user (the u_<id>_

of the object, which must agree with the source file's users/<id>/ directory; otherwise the call takes a spare). A user's calls only ever fork from a parent that only that user's calls used.

  • It never holds a call's data. Per call the server sends it one control

message with two fresh pipe fds attached (SCM_RIGHTS); the child takes them as its channel and speaks the ordinary protocol with the server. Source, payload, helper replies and the result travel only on those pipes, so no earlier caller's data is in the memory a child is forked from.

  • Each child is a single-use worker. Before the pipes even reach it, it

closes every fd of the fork server's, puts itself in a process group of its own (a group leader cannot setsid() out of the session), asks to die with its parent, sets RLIMIT_NPROC=0 and RLIMIT_CPU (the fork server keeps both: it must fork and it lives for many calls; memory, file-size and fd limits are inherited) and restricts itself with a second, nested Landlock domain, so Landlock refuses it ptrace of the fork server and, on ABI >= 6, signals to it. The fork server is also not dumpable. After the result the server asks the fork server to SIGKILL and reap that child; a child that forges a result and keeps running is killed all the same.

  • One child is forked ahead, between calls, and waits with all of that

set up; the run request is written into its pipe before the fork server confirms the handover. A call waits for neither a fork nor an extra round trip.

  • Fail closed. A fork server that cannot be started, answers late (2 s)

or wrongly, or dies is retired (the launcher then kills its whole session, children included), and that user's calls take spares for 60 seconds. With DBBASIC_USER_CODE_WARM_USERS=0, DBBASIC_USER_CODE_WARM_PARENTS=off, a Landlock ABI below 6 (unless opted in) or a launcher without the socket channel, every call takes a spare as before.

  • Said in the log. The fallback is silent for callers, so it is logged.

When a fork server or a spare exits or cannot be started, the server logs one warning (logger dbbasic.object_sandbox): the kind of worker and its pid, its exit status or signal (the launcher reports it for the workers it reaps; unknown with a launcher from before that, until its root-owned copy is replaced and restarted), how long it lived, and the memory limit it had. A second warning says that calls take the single-use path for 60 seconds. When the death looks like the memory limit (a MemoryError in its boot error or in what the interpreter wrote while starting, SIGKILL or SIGSEGV within 5 seconds of its start, or a failed exit within the first second) the line says so and names DBBASIC_USER_CODE_MEMORY_MB. Each cause is logged the first time, then at most once a minute with the number of repeats left out, so a crash loop cannot fill the log. The lines carry no object id, source, payload or user.

  • Bounded. Up to DBBASIC_USER_CODE_WARM_USERS (8) users have one; past

that the least recently used is retired. One idle for DBBASIC_USER_CODE_WARM_IDLE_SECONDS (600) is retired, and each is replaced after 1000 calls. A user's first call (and any call while their fork server is starting) takes a spare. Each fork server is about one idle worker of memory plus its forked-ahead child (copy-on-write; gc.freeze() before every fork keeps the pages shared).

What a child shares with the earlier children of the same fork server, and a spare would not: its parent's hash seed and memory layout (ASLR), for up to 1000 calls. Neither carries data; a child cannot learn another call's inputs from them.

GET /admin/status (capabilities.user_code_isolation.warm_parents) and object_sandbox.py --status say whether warm parents are on and how many run.

Helpers are proxies

Inside the worker _state_manager, _logger, _files and _runtime are proxies with the in-process method names and return shapes. Every call is one length-prefixed JSON message; the parent validates it (helper and method from a fixed allow-list, argument shapes, object handle), performs it with the ordinary object_state / object_logs / object_runtime_helpers code bound to that object's id, and replies. Exceptions come back with their class name and nearest builtin base, so except ValueError, except FileNotFoundError and except PermissionError behave as in-process.

Differences from in-process helpers, all deliberate:

  • _runtime.load_object applies the same rule as in-process (own namespace or

system objects; another user's id is CompositionDeniedError, even when it does not exist). A loaded object in the same namespace exposes execute, state_manager, file_manager and logger; its execute runs in another fresh sandboxed worker. A loaded system object exposes only execute and object_id; its state_manager/file_manager/logger raise PermissionError (in-process code could write any object's state that way).

  • A system object called from user code runs on the normal, non-sandboxed path

in the server process, with the identity of the request that started the chain: the parent replaces whatever _identity the user code put in the payload. That object is trusted code acting for that user; what it does with the payload is its responsibility, exactly as for an HTTP caller.

  • _files.files_dir raises PermissionError (a path the sandbox cannot open is

useless); put/get/delete/list/exists work.

  • _state_manager.update(..., after_set=...) raises TypeError (a callback

cannot cross the pipe); update(set_items) works.

  • _schedule / _unschedule are bound by the parent to the object the worker

is running: a call naming any other handle is a PermissionError. The user limits (60 s minimum, 10 schedules per user, both env-overridable) apply; see "Self-Scheduled Methods".

  • Results and payloads must be JSON-shaped (bytes are carried); a result that

is not becomes an ObjectWorkerError, as on the warm pool.

The parent is protected from its worker: a message over the size limit (the length prefix is checked before reading the body), malformed JSON, an unknown helper, method or handle, a malformed result, or more helper calls than the budget allows kills the worker and returns ObjectSandboxProtocolError. A wall-clock timeout kills it and returns ObjectExecutionTimeoutError (504). Results keep the ObjectExecutionResult shape, so HTTP responses for user objects are the same as for any other object.

Fail closed

User objects run only when all of these hold, and are otherwise refused with UserCodeIsolationUnavailableError (HTTP 503), logged once per reason on stderr:

  • a launcher answers on the socket and runs workers as a uid that is neither

root nor the server's (uid separation);

  • the kernel has Landlock ABI >= 4 (Linux >= 6.7; Ubuntu 24.04's 6.8

qualifies). ABI 4 adds TCP control. Before uid separation the floor was 6, because until ABI 6 a Landlocked process can still signal any process of its own uid -- the server included; as another uid it cannot;

  • the server is not root;
  • its private paths are closed to other users (see above).

No launcher means no user code, whatever the Landlock ABI: without uid separation the chmod/utime/stat hole above stays open, so a host with a new kernel but no launcher refuses user objects too. Admin, system and package objects keep working everywhere.

DBBASIC_USER_CODE_ISOLATION=unsafe-dev runs user objects through the same worker, scrubbed environment and proxies without Landlock or strict rlimits (and through the launcher when one is running). It is for development machines (macOS has neither Landlock nor the launcher) and must never be set on a server that accepts code from users. The test suite sets it automatically where the wall is missing.

python object_sandbox.py --status (run it as the server user: sudo -u dbbasic ..., or docker compose exec -u dbbasic ...) prints the verdict and each layer: uid_separation, sandbox_uid, network_namespace, landlock_abi, udp, and the reason when refused. Run as root or any other user it cannot reach the launcher: the verdict then says to run it as the service user, and the exit status is still 1. GET /admin/status reports the same under capabilities.user_code_isolation, and the server and daemon print the verdict at startup.

Settings

VariableDefaultMeaning
DBBASIC_USER_CODE_ISOLATION(unset: landlock)unsafe-dev runs without the wall (development only)
DBBASIC_USER_CODE_POOL_SIZE2already-sandboxed spare workers kept booted (refilled in the background)
DBBASIC_USER_CODE_WARM_PARENTSautoauto: warm parents only where Landlock ABI >= 6 scopes signals; on: also below (see "Warm parents" for the cost); off: never
DBBASIC_USER_CODE_WARM_USERS8users with a warm parent (fork server) at once; 0 turns warm parents off
DBBASIC_USER_CODE_WARM_IDLE_SECONDS600a warm parent unused this long is retired
DBBASIC_USER_CODE_TIMEOUT_SECONDS30wall clock per request when DBBASIC_OBJECT_TIMEOUT_SECONDS is 0
DBBASIC_USER_CODE_CPU_SECONDS10RLIMIT_CPU
DBBASIC_USER_CODE_MEMORY_MB512RLIMIT_AS; on a free-threaded Python build (3.13t, 3.14t) counted on top of the address space the interpreter has already reserved (about 1 GiB at start-up), because an absolute cap below that makes every later mapping fail
DBBASIC_USER_CODE_MAX_OPEN_FILES32RLIMIT_NOFILE
DBBASIC_USER_CODE_MAX_MESSAGE_BYTES8 MiBlargest single pipe message (request, helper call, result)
DBBASIC_USER_CODE_MAX_HELPER_CALLS10000helper calls per execution
DBBASIC_SANDBOX_LAUNCHER_SOCKET/run/dbbasic-sandbox/launcher.sockwhere the server finds the launcher
DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER3concurrent executions of one user's objects (0 = off); see "Fairness and quotas"
DBBASIC_USER_MAX_OBJECTS100objects one user may own (0 = off)
DBBASIC_USER_MAX_STATE_BYTES5 MiBone user object's whole state (0 = off)
DBBASIC_USER_MAX_FILES_BYTES100 MiBall of a user's _files storage (0 = off)
DBBASIC_SANDBOX_LAUNCHERonDocker entrypoint only: off starts no launcher (user objects are then refused)

Fairness and quotas

One customer must not be able to use up what everyone shares.

  • Concurrency. The server-wide cap on running objects

(DBBASIC_MAX_CONCURRENT_EXECUTIONS, 8) answered 503 Server is busy to everyone when one user sent 40 slow requests. A user's object now counts against its owner's own cap first (DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER, default 3: three busy users can fill the pool, one cannot). The user over the cap alone gets 429 with Retry-After: 1 and "limit": "user_object_executions"; the operator and system objects are not capped per user. A refused request takes no slot from the shared pool.

  • Quotas apply to u_<id>_* only; system objects are the operator's.

Objects: creating the 101st is 403 naming DBBASIC_USER_MAX_OBJECTS. State: one object's state may not grow past 5 MiB (the file is rewritten whole on every write, so a big one is also a slow one); the check sits where every state write ends, so the helpers, the sandbox proxy and the daemon are all covered, and the error names DBBASIC_USER_MAX_STATE_BYTES. A write that does not grow the file is always allowed, so an over-limit user can delete keys to recover. Files: _files.put counts all of a user's objects together against 100 MiB (413, naming DBBASIC_USER_MAX_FILES_BYTES); replacing a file counts only the difference. Worst case per user is objects x state cap plus the files cap. Set any of them to 0 to turn it off.

What system objects user code may call

User code (a sandboxed u_<id>_* object, for a request or for the daemon) may _runtime.load_object a system or package object only if that object opts in with a module-level USER_CALLABLE = True (read from the source, not executed, like HANDLES). Otherwise the load raises CompositionDeniedError naming the flag. The default is closed because a system object may have side effects (queue posts, admin state); opting in says "this object treats its caller as untrusted and checks request["_identity"] itself". Own-namespace objects need nothing. A second flag, LISTED = True, makes a system object appear in a customer's GET /objects (see the HTTP contract); it never changes who may run it.

Cost

Measured in Linux Docker on a Mac (OrbStack, Linux 7.2, Landlock ABI 10, Python 3.14), with the launcher (separate uid) as in production: a trivial GET through uvicorn over HTTP/1.1 keep-alive, 300 sequential calls, then 5 seconds of back-to-back calls from 1 and from 4 users at once (each user its own object). Two runs each; the ranges cover both.

Warm parents were on (ABI 10). On a kernel below ABI 6 they are off by default and the left column applies, with the spare-path improvements.

before (spares only)with warm parents
system object on the admin warm pool0.55 ms0.55 ms
user object, median / p95, 2 spares5.7-12.9 / 32-37 ms1.6 / 1.8 ms
user object, median / p95, 4 spares7.8-7.9 / 19-21 ms1.6-1.7 / 2.3 ms
user object making 10 helper calls, median6.6-8.8 ms2.1-2.2 ms
calls/s, 1 user (2 spares / 4 spares)68-69 / 110582-595
calls/s, 4 users at once147-161 (median 24-34 ms)906-930 (median 4.2 ms)

With a network namespace per worker (--cap-add SYS_ADMIN) the numbers are the same. Where the old time went, measured inside one call: the request itself (isolation check, reading the source, the pipe protocol, compiling and running the object, the result) was about 0.3 ms. The rest was waiting: 2-3 ms for the launcher to start the replacement spare (it was on the request path), about 3 ms while the worker finalised its interpreter on the core the server was waiting for, and, under steady load, waiting for a spare to finish booting -- a boot costs about 42 ms (21 ms interpreter start, 12 ms of which 9 were importing traceback, 4 ms preloads, 2 ms Landlock), so two or four spares cannot keep up with calls arriving every few milliseconds. Each of those is fixed: spares refill in the background, a worker leaves with os._exit once it has answered, boots skip traceback, and a recent user's calls are forked from their warm parent. A warm call now spends about 0.4 ms handing the pipes over and 0.1-0.2 ms having its child reaped; one helper call is a 0.04 ms round trip, and compiling an object's source about 0.03-0.1 ms, so neither batching helpers nor caching compiled code would buy much.

A user's first call, and a call while their warm parent is starting or after it failed, takes a spare and costs what it did before (with the refill now off the path). On this machine, calls that arrive after the CPUs have gone idle take several times longer on both paths (the virtual machine's cores wake slowly); the table is back-to-back load.

Uid separation costs nothing measurable: the same benchmark over HTTP inside the container (OrbStack, Landlock ABI 10, default 2 spares, three runs of 200 sequential GETs each) gave a user-object median of 12.1-15.4 ms before the launcher and 11.5-14.7 ms with it (10-15.5 ms with a network namespace per worker under --cap-add SYS_ADMIN); p95 stayed around 30-37 ms throughout.

What user code can and cannot do

Can: compute in Python, import the standard library and installed packages, use its own state, logs and files, call its own namespace's objects and call system objects that opted in with USER_CALLABLE = True (which act with the requester's identity).

Cannot: read environment secrets, read or list any file outside the Python installation (no /etc/passwd, data directory, other users' state or source, server code, its own source file), write any file, change any file's mode, times or owner, stat anything in the data or objects directories (another customer's object and a missing one give the same EACCES), create processes or threads, execute programs, open TCP connections or listen, signal the server, or outlive its request. With a network namespace (or on ABI >= 6) it also cannot connect to abstract UNIX sockets.

What this does not cover

  • UDP and other socket families without a network namespace: they are

mediated only when the running kernel's Landlock has rights for them (the ABI 10 kernel tested here does; ABI 4 does not). So in Docker on Ubuntu 24.04 (ABI 4, no CAP_SYS_ADMIN) user code can send UDP datagrams; the status says udp: NOT controlled. On a bare VM the systemd unit's network namespace and address-family filter block it.

  • Signals between concurrent workers on ABI < 6: they share the sandbox

uid, so one user's object can kill another user's worker that is running at the same moment (that request fails; no data is reachable). The same goes for another user's warm parent when an operator has opted in to warm parents below ABI 6 (DBBASIC_USER_CODE_WARM_PARENTS=on; they are off there by default): killing it sends that user's calls to spares for a while; stopping it makes their next call wait the 2-second control timeout before it is retired. Landlock refuses ptrace across these domains on every ABI. A PID namespace or a uid per worker would close this; neither is built.

  • A warm parent's children share its network namespace (one per user,

not one per call) when the launcher has CAP_SYS_ADMIN: it is still empty, but two calls of the same user running at the same moment could reach each other's abstract UNIX sockets on ABI < 6. Nothing outlives a call, so nothing carries to a later one.

  • Abstract UNIX sockets on ABI < 6 without a network namespace: a worker

can reach abstract sockets other processes in the same network namespace listen on.

  • Metadata of world-readable paths: stat works on the code directory

and on the data and objects directories themselves (not their contents), as on any file the sandbox user may traverse to.

  • CPU, cache and timing side channels between processes on the same host.
  • Kernel bugs, including in Landlock itself.
  • Resource exhaustion inside the limits: up to the CPU, memory and

timeout limits per request, times the per-user concurrent-execution cap (and the server-wide one across users); storage up to the per-user quotas. Logs are not quota-limited (they rotate).

  • Anything a system object does when user code calls it.
  • Pathname UNIX sockets on kernels whose Landlock has no right for them

(the launcher's own socket is out of reach: its directory is closed to the sandbox user, and it answers only the server's uid).

  • The launcher itself runs as root: a bug in it is a root bug. It is kept

short, stdlib only, single-threaded, and reads nothing but fixed-size, allow-listed requests from one uid.

Storage Boundary

The default runtime storage is file-backed:

  • object source under objects/
  • object state under data/state/
  • object logs under data/logs/
  • object versions under data/versions/
  • object source changes under data/source_changes/
  • object file changes under data/file_changes/
  • object-owned files under data/files/
  • collection records under data/collections/
  • collection record changes under data/record_changes/
  • collection schemas under data/schemas/

SQL databases, SQLite, external HTTP APIs, and AI APIs are optional integrations. They should be reachable from objects or packages when needed, but the base runtime should not require a database service before the first useful app can run.

That boundary is intentional. It keeps the single-VM deployment small, makes backup/restore understandable, and lets Scroll inspect source, state, logs, versions, schemas, and diagrams without turning SQL into the default storage contract.

Runtime backups should use object_backup.py. The portable archive contains object source plus data/state/, data/logs/, data/versions/, data/source_changes/, data/schema_versions/, data/record_changes/, data/package_changes/, data/file_changes/, data/files/, data/schemas/, and data/collections/. It deliberately leaves deployment secrets, service files, virtualenvs, git history, lock files, temp files, and ephemeral rate-limit files outside the archive.

Object Execution Result

Public code should use object_execution.py for the shared execution result shape. The future ASGI server, daemon, Scroll execute button, and AI repair loop should all be able to depend on the same fields:

  • object_id
  • method
  • path
  • ok
  • result
  • error
  • started_at
  • finished_at
  • duration_ms

Execution failures should be captured as data instead of being flattened into plain strings. Error data includes:

  • type
  • message
  • traceback

This is part of the 100x dev loop: execute an object, inspect the structured error and traceback, patch the source, and keep the version trail close to the runtime feedback.

User objects see only their own frames. When a user-namespace object (u_<id>_*) raises, the error message carries the exception type and text plus the frames from the user's own source file only, shown by file name (File "hello.py", line 5, in GET) with line numbers relative to that file. Server frames and absolute paths (/opt/..., the data directory) are left out, and the structured traceback field is empty. System and admin objects keep the full traceback.

Object HTTP Responses

The runtime returns plain Python values. The ASGI/web layer turns those values into HTTP responses.

Compatibility response shapes:

return {"status": "ok", "count": 1}

Normal dicts are JSON responses and are not wrapped in another envelope.

return {
    "content_type": "text/html; charset=utf-8",
    "body": "<!doctype html><h1>DBBASIC</h1>",
}

Dicts with content_type and body become raw HTTP responses. The body may be text or bytes. This is the object shape used by generated views, HTML pages, and binary/image objects.

return (201, [("Content-Type", "text/plain")], [b"created"])

Tuples in (status, headers, body) form are passed through as low-level HTTP responses. body may be bytes, text, or a list of bytes/text parts.

Plain string returns are served as text/html; charset=utf-8. Plain bytes returns are served as application/octet-stream.

Object Versions

Public code should use object_versions.py for source version storage. The storage format intentionally matches the working prototype:

data/versions/{object_id}/metadata.tsv
data/versions/{object_id}/v1.txt
data/versions/{object_id}/v2.txt

metadata.tsv fields are:

  • version_id
  • timestamp
  • author
  • message
  • hash

History is returned newest first and does not include source content. Fetching a specific version returns metadata plus content.

Rollback is non-destructive. Rolling back to version N creates a new latest version containing the old content, preserving the full history.

The future runtime should keep the prototype behavior:

  • save an initial version when an object is first loaded and no history exists
  • on source update, save the new code as a version, write it to the source file,

reload the object, and log the update

  • on rollback, create the rollback version, write it to the source file, reload

the object, and log the rollback

Public server/runtime code should use object_source.py for the source file read, update, and rollback steps so source writes and version storage do not drift into separate implementations.

Object Source Changes

Public code should use object_source_changes.py for source edit and rollback activity storage. This is separate from data/versions/: versions store recoverable source snapshots, while source changes store the operator timeline that Scroll can show as admin activity.

Source changes are append-only JSON Lines:

data/source_changes/{object_id}/changes.jsonl

The helper exposes:

append_source_change(object_id, action, version_id, from_version_id=None, actor="api", message="", correlation_id=None, details=None, base_dir="data")
list_source_changes(object_id, base_dir="data", limit=100, offset=0)

Entries include change_id, timestamp, object_id, action, version_id, from_version_id, actor, message, correlation_id, and details. History is returned newest first and does not include source content.

Object File Changes

Public code should use object_file_changes.py for object-owned file write activity storage. This is separate from data/files/: files store current content, while file changes store the operator timeline for uploads, overwrites, and deletes.

File changes are append-only JSON Lines:

data/file_changes/{object_id}/changes.jsonl

The helper exposes:

append_file_change(object_id, action, file_name, file_size=None, actor="api", message="", correlation_id=None, details=None, base_dir="data")
list_file_changes(object_id, file_name=None, base_dir="data", limit=100, offset=0)

Entries include change_id, timestamp, object_id, action, file_name, file_size, actor, message, correlation_id, and details. History is returned newest first and does not include file content.

State Manager Interface

The daemon expects trigger objects to expose a state manager with:

state_manager.reload()
state_manager.get_all()
state_manager.get(key)
state_manager.set(key, value)

Values used by scheduler, queue, and events are JSON strings stored by key.

State storage intentionally matches the working prototype:

data/state/{object_id}/state.tsv

Rows are either:

key<TAB>value
key<TAB>value<TAB>timestamp

The public state reader skips an optional key<TAB>value<TAB>timestamp header, ignores malformed rows, and coerces values to int, then float, otherwise keeps strings.

The public runtime-owned state manager writes sorted rows in timestamp format:

key<TAB>value<TAB>timestamp

There is still no public HTTP state-write endpoint. Object code writes state through _state_manager.

Log Storage

Log storage intentionally matches the working prototype:

data/logs/{object_id}/log.tsv
data/logs/{object_id}/log-*.tsv
data/logs/{object_id}/log-*.tsv.gz

Rows are TSV with a header. The default fields are:

  • entry_id
  • timestamp
  • level
  • message
  • method
  • status
  • duration_ms
  • error_type
  • error

Object code may add extra fields such as method, user_id, or request metadata. The public log reader returns the current log.tsv first, then rotated log-*.tsv and log-*.tsv.gz files in sorted order, and supports exact level filtering and limit.

The active log.tsv stays plain TSV so appends, tail, and crash recovery stay simple. When it reaches the configured size limit, the runtime rotates it to a timestamped file and gzip-compresses the rotated file by default.

Log maintenance settings:

  • DBBASIC_LOG_MAX_BYTES controls active log size before rotation. The default

is 10485760 bytes. Values less than or equal to 0 disable rotation.

  • DBBASIC_LOG_COMPRESS_ROTATED controls gzip compression of new rotated logs.

The default is true. Set it to false for plain rotated TSV files.

  • DBBASIC_LOG_KEEP_ROTATED controls garbage collection of rotated logs. The

default is 32. Values less than or equal to 0 keep all rotated logs.

Compressed rotated logs remain ordinary files on disk. Operators can inspect them without expanding a second copy:

gzip -cd data/logs/site_home/log-*.tsv.gz

This is at-rest compression. HTTP response compression, log replication compression, and backup-transfer compression are separate transport concerns. Those should compress larger batches or responses, not tiny realtime events by default.

The public ASGI execution path appends one log entry after each object method run. Successful runs use DEBUG with status=success; failed runs use ERROR with status=error, error_type, and error.

Loaded object modules also receive _logger. The public logger helper writes to the same per-object TSV path and exposes:

_logger.log(level, message, **fields)
_logger.debug(message, **fields)
_logger.info(message, **fields)
_logger.warning(message, **fields)
_logger.error(message, **fields)
_logger.critical(message, **fields)
_logger.get_logs(level=None, limit=None, offset=0, **filters)

This keeps object-owned application logs and runtime execution logs together without creating a second logging format.

Object Files

Object-owned files live under:

data/files/{object_id}/

The public helper module is object_files.py. It exposes read helpers plus write helpers that the HTTP layer must gate behind admin auth, permissions, size limits, and deployment flags:

list_object_files(object_id, base_dir="data")
read_object_file(object_id, filename, base_dir="data")
write_object_file(object_id, filename, content, base_dir="data", overwrite=False)
delete_object_file(object_id, filename, base_dir="data")

list_object_files returns dictionaries with:

  • name
  • size
  • modified

read_object_file returns raw bytes plus the same metadata. Filenames are validated before filesystem access. Empty names, absolute paths, null bytes, and .. traversal are rejected.

Upload and delete are intentionally not public yet. They need explicit request size limits, content policy, audit logs, and server-enforced permissions.

Object Collections

Collections are a read-only derived view. The public helper modules are object_collections.py and object_records.py.

The server infers collection names from object IDs:

  • site_home belongs to site
  • apps_widget_counter belongs to apps
  • u_42_deals belongs to deals

Permission rules can also name a collection before any object exists for it. Record files can name a collection before any object exists for it too. That lets Scroll show planned or data-backed collections while the server keeps /objects as the stable source of executable behavior.

Collection summaries include:

  • object count
  • object owner set
  • object kind counts
  • object-owned file count
  • number of objects with state
  • number of objects with logs
  • whether a TSV record file exists
  • exact permission rule summary for that collection

The log portion is intentionally a cheap file-presence check. Listing collections should not scan every log entry on a busy server.

Collection records live under:

data/collections/{collection}/records.tsv

The TSV file must have a header row and an id column. The current public record API is:

list_collection_records(collection, base_dir="data", limit=100, offset=0)
read_collection_records(collection, base_dir="data")
get_collection_record(collection, record_id, base_dir="data")
create_collection_record(collection, record, base_dir="data")
update_collection_record(collection, record_id, changes, base_dir="data")
delete_collection_record(collection, record_id, base_dir="data")

Values are stored and returned as strings. Record writes preserve existing columns and append new columns from submitted fields. Record IDs are unique and cannot be changed by update.

New DBBASIC-facing record IDs are UUIDv4 strings by default when the server creates them. Imported application data can keep legacy IDs in compatibility columns, but new URLs, generated UI, change logs, and object references should not depend on sequential database integers. This came from the Django/PostgreSQL migration path: existing tables may arrive with integer primary keys and JSONB-style flexible data, while new DBBASIC resources need stable, non-enumerable IDs that can move between object servers and packages.

If a manual schema exists for the collection, create/update validates known fields before writing the TSV:

  • required: true, validation.required, and validation.not_null require a

non-empty value

  • default fills missing or empty fields during create
  • type can validate integer, number, currency, boolean, date,

datetime, and enum

  • enum, validation.choices, or validation.in restrict allowed values
  • validation.min, validation.max, validation.min_length,

validation.max_length, validation.pattern, and validation.regex are enforced

  • type: "computed", computed, or read-only metadata rejects submitted

writes for that field

Unknown fields are still allowed. This preserves the DBBASIC rule that schemas can tighten important collections without turning every object into a migration project.

Schemas are metadata, not a mandatory deployment gate. A collection can start schemaless, accept extra fields, and later add schema metadata for generated forms, validation, relations, field permissions, and admin views. This keeps the fast object/data loop while still allowing stricter app surfaces when needed.

The HTTP record routes are admin-gated by default. When permission audit or enforcement is enabled, read routes use the server permission policy. Record lists apply row filters before pagination; record detail checks evaluate the selected row and can redact fields. Record writes require either the admin token or enforcement mode with an allowed create, update, or delete decision. Audit-only mode records write decisions without granting mutation access. When enforcement is enabled, schema field permissions are also applied: hidden fields are removed from record reads, and submitted fields with read or hidden access are rejected before the TSV write.

Record mutations also append change entries under:

data/record_changes/{collection}/changes.jsonl

The public helper module is object_record_changes.py. It exposes:

append_record_change(collection, record_id, action, before, after, base_dir="data")
list_record_changes(collection, record_id=None, base_dir="data", limit=100, offset=0)

Request/action correlation IDs are UUIDv4 values. The ASGI app accepts X-DBBASIC-Correlation-ID, normalizes it only when it is a valid UUIDv4, and otherwise creates a new one. Source versions, source-change entries, object-owned logs, execution errors, and permission audits should carry the current correlation ID so Scroll and AI tooling can trace one action across code, data, logs, and rollback history.

Entries are JSON Lines with:

  • change_id
  • timestamp
  • collection
  • record_id
  • action
  • actor
  • message
  • changed_fields
  • before
  • after

New change_id values are UUIDv4. Old timestamp-shaped change IDs remain readable so existing package and record history can be migrated in place.

This is the durable record history that Scroll can show in admin and rollback screens. It is intentionally separate from event delivery. Scheduler, queue, and event trigger objects can later publish notifications from the same facts without making callback delivery the only audit trail.

Collection Schemas

Schema metadata lives under:

data/schemas/{collection}.json

The public helper module is object_schemas.py. It exposes read and admin-write operations:

list_schemas(base_dir="data")
get_schema(collection, base_dir="data")
replace_schema(collection, payload, base_dir="data")

A schema file can describe fields, validation rules, computed values, UI hints, field permissions, and relations:

{
  "title": "Invoices",
  "version": 1,
  "fields": [
    {
      "name": "customer_id",
      "type": "relation",
      "required": true,
      "relation": {"collection": "contacts"},
      "validation": {"not_null": true}
    },
    {
      "name": "cost_price",
      "type": "currency",
      "permissions": {"admin": "edit", "sales": "hidden"},
      "ui": {"section": "totals"}
    }
  ]
}

If a collection exists but no manual schema file exists, the server can return an empty derived schema. That lets Scroll render the collection first and add field metadata later without breaking the object API.

Schema metadata is not the permission system by itself. Permission rules still control access modes, ownership, sharing, row filters, and field allow/deny lists. Schema fields tell tools what exists and can refine individual edit/read/hidden field behavior for generated forms. The server enforces those schema field permissions only after the broader policy has allowed the row.

Schema writes are available through the admin-only replacement path. They are atomic file replacements under data/schemas/ and preserve UI/view metadata so Scroll can save generated form, table, dashboard, validation, relation, and field permission definitions.

Every admin schema write also records a schema version under:

data/schema_versions/{collection}/metadata.tsv
data/schema_versions/{collection}/vN.json

Rollbacks are non-destructive. A rollback creates a new latest version from an older schema JSON file and then replaces data/schemas/{collection}.json. This gives admin tools and Scroll a change log for who changed a schema, what message they left, and what can be restored. User-level schema editing still needs real sessions and broader permission checks before it should be exposed outside trusted admin tooling.

Scheduler State

Scheduler state keys begin with:

task_

Each value is a JSON object with fields such as:

  • id
  • object_id
  • method
  • payload
  • type
  • schedule
  • status
  • next_run
  • last_run
  • run_count
  • last_error, last_error_at, consecutive_failures (only once a run has

failed)

type is cron (needs croniter), onetime (an ISO timestamp) or interval (whole seconds, counted from the last run). The daemon executes active tasks when next_run is due.

Self-Scheduled Methods

_schedule(interval_seconds, method_name) and _unschedule(method_name=None) (object_schedule.py) are the askrobots runtime's helpers, backed by this board instead of a dict in one process. A self-scheduled row carries "kind": "object_method", "type": "interval", and the id obj.<object_id>.<method> (state key task_obj.<object_id>.<method>), so there is one row per (object, method) and scheduling again is an upsert; an unchanged interval leaves the row untouched.

For these rows method is a function name, not an HTTP verb. The daemon runs it with ObjectExecutionRequest(named_method=True) through execute_object: user objects in the sandbox, system objects in-process, with an empty payload and no _identity -- the object acts as itself, never as the admin. The function is called with no arguments unless its signature needs one. Only the daemon sets named_method; HTTP and _runtime callers reach only the verb methods, so scheduling by name opens no new entry point.

A run that raises, times out or is killed (for example for memory) is recorded on the row: last_error (the message, up to 500 characters), last_error_at (epoch seconds) and consecutive_failures, which the next success resets to 0 (last_error stays, so "it failed once on Tuesday" can still be read). It also writes an ERROR line to the target object's own log (GET /objects/{id}?logs=true), and the scheduler board shows "failing xN" with the reason. A run that raised still counts in run_count; a skipped one (below) does not.

A task whose object or method has gone is skipped, gets an error field, counts as a failure like the above and is logged once per daemon start; it keeps its interval in case the object comes back. DELETE /objects/{id}?destroy=true removes the object's self-scheduled rows (not the schedules a package declared). The daemon writes run bookkeeping back under the state lock and never re-creates a row the method removed while it ran.

Every refusal from _schedule/_unschedule raises ScheduleError (a ValueError subclass), in system objects and in the sandbox alike: a bad interval or name, a method the object lacks, the per-user cap, extra arguments. The HTTP verb names GET, POST, PUT, DELETE, PATCH, HEAD and OPTIONS are refused as method names; schedule a function with its own name. An owner reads their object's schedules with GET /objects/{id}?schedules=true (http-api-contract.md).

Limits: minimum interval DBBASIC_SCHEDULE_MIN_INTERVAL_SECONDS (default 5) for system objects and DBBASIC_SCHEDULE_USER_MIN_INTERVAL_SECONDS (default

  1. for user objects; at most DBBASIC_SCHEDULE_USER_MAX_TASKS (default 10)

self-scheduled rows across one user's objects. The board is bounded by construction: one row per object method.

Queue State

Queue state keys begin with:

msg_

Each value is a JSON object with fields such as:

  • id
  • queue_name
  • message
  • priority_level
  • status
  • created_at
  • visible_after
  • expires_at
  • attempts
  • max_attempts

message should include:

  • object_id
  • method
  • payload

The daemon marks messages as processing, completed, pending, expired, or failed.

Event State

The public helper module is object_events.py. It writes event and subscription state into:

data/state/events/state.tsv

This keeps the HTTP API, Scroll, and the daemon on one event shape.

Event subscription keys begin with:

sub_

Event keys begin with:

event_

Subscriptions include:

  • id
  • event_type
  • callback_url
  • last_event_id
  • delivery

Events include:

  • id
  • event_type
  • payload
  • source
  • actor
  • timestamp
  • created_at

The daemon delivers matching events to the subscription callback URL and records delivery status on the subscription. delivery.status is idle, ok, or failed, with attempt counts, success/failure counts, the last HTTP status code, and the last error text. last_event_id advances only after successful delivery. A failed callback leaves the cursor in place so the daemon can retry instead of silently skipping the event.

The current HTTP event API is admin-gated:

GET /events
POST /events
DELETE /events?keep_count=1000&keep_seconds=604800
GET /events/deliveries
GET /events/subscriptions
POST /events/subscriptions
DELETE /events/subscriptions?event_type=invoice.created&subscriber_id=scroll
Authorization: Token <token>

Record change history is still the durable audit trail. Events are for notifications, triggers, listeners, webhooks, and future worker/actor-style flows that need to react to those facts. By default, collection record POST, PUT, and DELETE mutations publish metadata-only collection.record.created, collection.record.updated, and collection.record.deleted events from the saved change entry. Set DBBASIC_ENABLE_RECORD_EVENTS=false to disable that publication path.

Record mutation event payloads include change_id, collection, record_id, action, actor, timestamp, and changed_fields. They do not include full before or after snapshots until subscriber permission filtering exists.

Event retention is built into the server and daemon cleanup path. The default is to keep the newest 1000 events and prune events older than seven days. Configure that with:

DBBASIC_EVENT_KEEP_COUNT=1000
DBBASIC_EVENT_KEEP_SECONDS=604800

Set either value to 0 to disable that part of pruning. Pruning deletes only event_ rows. It does not delete sub_ rows, and it protects the event id held by any subscription last_event_id so the daemon does not lose its delivery cursor. If a subscription has a failed delivery attempt, pruning also protects the failed event id so retry state remains visible to Scroll and the daemon.

Daemon posture is exposed through an admin-token-gated read-only endpoint:

GET /daemon/status
Authorization: Token <token>

The response summarizes trigger source presence, scheduler task counts, due tasks, queue message counts, visible and delayed pending messages, event counts, subscription delivery status, pending deliveries, event retention settings, and rate-limit cleanup pressure. It does not execute daemon work and does not expose event payloads. This gives Scroll a Flower-style operator view without adding a separate queue dashboard service to the single-VM deployment.

Trusted operators can also manage scheduler tasks and queue messages through admin-token-gated routes:

GET /daemon/scheduler/tasks
POST /daemon/scheduler/tasks
PATCH /daemon/scheduler/tasks/{task_id}
DELETE /daemon/scheduler/tasks/{task_id}
GET /daemon/queue/messages
POST /daemon/queue/messages
PATCH /daemon/queue/messages/{message_id}
DELETE /daemon/queue/messages/{message_id}

These routes write the same task_ and msg_ rows that object_daemon.py already polls. Task and message payloads are redacted by default so Scroll can show operator posture without leaking secrets into broad status views. Use include_payload=true only for trusted admin screens.

Packages

Packages are the DBBASIC way to ship reusable app pieces without turning every app into a separate deploy process. A package is a directory containing a manifest plus package-owned objects, schemas, permissions, seed data, and migrations:

The intended package catalog starts from reusable app primitives: messages, projects, tasks, notes, files, articles, links, contacts, finance, events, workers, templates, catalog entries, time tracking, AI usage, objects, forums, documentation, and APIs. Those pieces should be installable and inspectable as packages, not buried inside one private monolith.

packages/{package_id}/
  dbbasic-package.json
  objects/
  schemas/
  permissions/
  seed/
  migrations/

Package source can be overridden with:

DBBASIC_PACKAGES_DIR=/path/to/packages

The current public helper module is object_packages.py. It exposes package discovery, non-mutating install planning, and conservative install writes:

list_packages(root="packages")
get_package(package_id, root="packages")
dry_run_package(package_id, root="packages", base_dir="data", object_roots=None)
install_package(package_id, root="packages", base_dir="data", object_roots=None, allow_replace=False)

The manifest format is JSON so Python 3.10 installs do not need another parser. The first required manifest is:

{
  "id": "hello-world",
  "name": "Hello World",
  "version": "0.1.0",
  "description": "Minimal DBBASIC package",
  "compatibility": {"object_server": ">=0.0.1"},
  "dependencies": [],
  "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
  "schemas": [],
  "permissions": [],
  "seed": [],
  "migrations": []
}

Package paths are package-relative. Absolute paths, null bytes, and .. traversal are rejected. Dry-runs report what would be created, replaced, merged, applied, or skipped without writing object source or data.

The first install contract is intentionally conservative:

  • objects are written under the configured object root
  • schemas are validated and written under data/schemas/
  • seed TSV is created only when the target collection records file does not

already exist

  • existing objects and schemas require allow_replace=True
  • permission fragments ({"rules": [...]}) are validated, stamped with

package provenance, and merged into the deployment policy, skipping rules that already exist so reinstalls stay idempotent; invalid fragments block the install

  • before that merge, rules the package has withdrawn are retired: a live rule

tagged as this package's and identical to one in the package's recorded baseline that it no longer ships, or to one in the fragment's retracted list, is removed and reported in permission_retractions; untagged and hand-edited rules are left and reported (permissions-model.md, "Package Rules And Upgrades")

  • migrations are rejected until explicit run semantics are added

Package change history lives here:

data/package_changes/{package_id}/changes.jsonl

The public helper module is object_package_changes.py. It exposes:

append_package_change(package_id, action, package_version=None, actor="api", details=None, base_dir="data")
get_package_change(package_id, change_id, base_dir="data")
list_package_changes(package_id, base_dir="data", limit=100, offset=0)
dry_run_change_details(plan)

The current server appends a dry_run change for GET /packages/{package_id}?dry_run=true. It appends install_requested and then either installed or failed for POST /packages/{package_id}/install. The details are intentionally compact: package identity, safe/install flags, action counts by package section, and warnings. Successful installs include restore-point metadata. Package source is not copied into the changelog.

Package install writes require both admin auth and:

DBBASIC_ENABLE_PACKAGE_INSTALLS=true

The HTTP install route creates a runtime restore point before object, schema, or seed writes. Restore points default to data/backups/; set DBBASIC_BACKUPS_DIR to place them on a separate backup volume.

Package restore is a separate admin-gated route:

POST /packages/{package_id}/restore
DBBASIC_ENABLE_PACKAGE_RESTORE=true
{"change_id": "...", "confirm": "restore-runtime"}

The change id must refer to a package change that contains restore-point metadata. The server restores that runtime snapshot with overwrite and prune-extra enabled, then records restore_requested and rolled_back package change rows after the restore completes. This is a whole-runtime restore point, not a selective package uninstall.

Keep this disabled on public staging unless the route is on a private admin surface and backups have been tested.

Public Safety

Tests and docs should use only safe placeholder values:

  • 127.0.0.1 for localhost samples
  • 192.0.2.0/24, 198.51.100.0/24, or 203.0.113.0/24 for documentation IPs
  • example.com, example.net, or example.org for documentation domains

Do not commit real deployment IPs, hostnames, tokens, private URLs, or personal filesystem paths.