diff --git a/deploy/aligned-tunnel.service b/deploy/aligned-tunnel.service new file mode 100644 index 0000000..b92c669 --- /dev/null +++ b/deploy/aligned-tunnel.service @@ -0,0 +1,33 @@ +[Unit] +# The tunnel, and the ordering here is a safety property rather than a +# preference. `Requires=aligned-proxy.service` means this cannot be what is +# running if the proxy is not: without it, a tunnel that came up first — or +# stayed up after the proxy crashed — would be a public door with nothing +# behind it checking who is asking. This tunnel serves both hostnames: +# aligned.click (the product) and agent.aligned.click (the opencode agent). +Description=aligned.click Cloudflare tunnel +After=network-online.target aligned-proxy.service +Requires=aligned-proxy.service +BindsTo=aligned-proxy.service +Wants=network-online.target + +[Service] +Type=simple +User=aligned +Group=aligned +WorkingDirectory=/opt/aligned.click +# cloudflared finds its credentials in ~/.cloudflared, from the tunnel name and +# cert.pem. Those two files are account credentials and are copied to this +# machine by hand — they are not in the repo and must not be. +ExecStart=/usr/local/bin/cloudflared tunnel --config /opt/aligned.click/deploy/tunnel.yml run +Restart=always +RestartSec=5 + +NoNewPrivileges=yes +PrivateTmp=yes +ProtectSystem=full +ProtectHome=true +RestrictSUIDSGID=yes + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/deploy/install.sh b/deploy/install.sh index ff9912c..d65e2f2 100755 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -1,48 +1,151 @@ -#!/bin/sh -# Install the aligned.click systemd services and the Cloudflare tunnel. +#!/usr/bin/env bash +# Install the aligned.click product stack as systemd services on this machine. # -# sudo ./deploy/install.sh +# sudo ./deploy/install.sh [APP_DIR] # -# Assumes /opt/aligned.click is this repo (or a checkout), that .venv is built -# there, and that `cloudflared` is installed. The oauth sidecar needs its -# deps: cd auth/oauth && npm install (once, first time). +# APP_DIR defaults to /opt/aligned.click. The unit files are rendered with +# that path and the service user substituted in, so the same repo deploys to a +# home-dir checkout (SERVICE_USER=atproto-server ./deploy/install.sh +# ~/feed.aligned.click) or the /opt layout. Assumes .venv is built there and +# the oauth sidecar deps are installed (cd auth/oauth && npm install --omit=dev). +# +# What it does NOT do, deliberately: +# +# - **It does not bring your secrets.** .env, ~/.cloudflared/ and the provider +# key are not in the repo and are not invented here. The script tells you +# which are missing and refuses to pretend the service is working without +# them. +# - **It does not open a port.** Nothing here listens outside loopback except +# through the Cloudflare tunnel, which is an outbound connection. +# - **It does not run the services as root.** They run as the service user, and +# the only reason this needs sudo at all is to write unit files into /etc. +set -euo pipefail -set -e +SERVICE_USER="${SERVICE_USER:-aligned}" +REPO="${1:-/opt/aligned.click}" +UNITS=(aligned-oauth aligned-proxy aligned-app aligned-feedgen aligned-ingest aligned-tunnel) -APP=${1:-/opt/aligned.click} -SERVICES="aligned-oauth aligned-proxy aligned-app aligned-feedgen aligned-ingest" +red() { printf '\033[31m%s\033[0m\n' "$*"; } +green(){ printf '\033[32m%s\033[0m\n' "$*"; } +warn() { printf '\033[33m%s\033[0m\n' "$*"; } +step() { printf '\n\033[1m%s\033[0m\n' "$*"; } -# A dedicated non-root user for every service. The services only ever write -# under private/, and ProtectSystem=strict makes the rest of the filesystem -# read-only to them. -if ! id -u aligned >/dev/null 2>&1; then - useradd --system --home-dir "$APP" --shell /usr/sbin/nologin aligned -fi +[ "$(id -u)" -eq 0 ] || { red "run this with sudo — it writes unit files to /etc/systemd/system"; exit 1; } +id "$SERVICE_USER" >/dev/null 2>&1 || { + if [ "$SERVICE_USER" = aligned ]; then + useradd --system --home-dir "$REPO" --shell /usr/sbin/nologin aligned + else + red "no user '$SERVICE_USER'. Create it, or set SERVICE_USER=… and re-run."; exit 1 + fi +} + +USER_HOME="$(getent passwd "$SERVICE_USER" | cut -d: -f6)" +run_as() { sudo -u "$SERVICE_USER" -H bash -lc "$*"; } + +# Where a runtime is, if it is anywhere. Asking `command -v` alone was wrong and +# quietly so: run_as is a login shell, and that shell's PATH is the system +# default — it carries neither ~/.local/bin nor ~/.opencode/bin, which is where +# this script installs all three of these. So nothing it installed was ever +# found again, and every run reinstalled everything. Node tolerated that (a +# directory swap and a symlink); cloudflared did not, and took the deploy with +# it. Look in the place we install to, after the PATH and before giving up. +runtime() { # runtime + local found + found="$(run_as "command -v $1" 2>/dev/null || true)" + [ -n "$found" ] || { [ -x "$2" ] && found="$2"; } || true + printf '%s' "$found" +} + +# ---------------------------------------------------------------- runtimes +# +# Everything is installed into the service user's home rather than system-wide. +# Nothing else on this machine wants these versions, and an install that lives +# in one directory is an install you can delete. + +step "runtimes" + +PYTHON="$REPO/.venv/bin/python" +[ -x "$PYTHON" ] || { red "$PYTHON does not exist — build it: python3 -m venv $REPO/.venv && $PYTHON -m pip install -r $REPO/requirements.txt"; exit 1; } +echo " python $PYTHON" + +NODE="$(runtime node "$USER_HOME/.local/bin/node")" +[ -n "$NODE" ] || { red "node is not installed"; exit 1; } +echo " node $NODE" + +CLOUDFLARED="$(runtime cloudflared "$USER_HOME/.local/bin/cloudflared")" +[ -n "$CLOUDFLARED" ] || { red "cloudflared is not installed"; exit 1; } +echo " cloudflared $CLOUDFLARED" + +# ---------------------------------------------------------------- the code + +step "the code" -# The services read .env at boot. It holds GREENPT_API_KEY and the index app -# password, so it must not be world-readable — a leaked key means paid model -# calls under our account. -chmod 600 "$APP/.env" 2>/dev/null || true -chown aligned:aligned "$APP/.env" 2>/dev/null || true +chown -R "$SERVICE_USER":"$SERVICE_USER" "$REPO" +echo " owner $SERVICE_USER" + +# ---------------------------------------------------------------- config + +step "config" + +ENV_FILE="$REPO/.env" +[ -f "$ENV_FILE" ] || { install -m 600 -o "$SERVICE_USER" -g "$SERVICE_USER" /dev/null "$ENV_FILE"; } +chmod 600 "$ENV_FILE"; chown "$SERVICE_USER":"$SERVICE_USER" "$ENV_FILE" # private/ is the one writable subtree. Make sure it exists and is ours. -mkdir -p "$APP/private" -chown -R aligned:aligned "$APP/private" 2>/dev/null || true +install -d -m 700 -o "$SERVICE_USER" -g "$SERVICE_USER" "$REPO/private" +chown -R "$SERVICE_USER:$SERVICE_USER" "$REPO/private" + +missing=() +grep -q '^GREENPT_API_KEY=.\+' "$ENV_FILE" \ + || missing+=("GREENPT_API_KEY=… in .env (the model provider's key — every user's turns bill to it)") +grep -q '^INDEX_BLUESKY_HANDLE=.\+' "$ENV_FILE" \ + || missing+=("INDEX_BLUESKY_HANDLE=… in .env (the crawler's read-only search account)") +grep -q '^ADMIN_DID=' "$ENV_FILE" \ + || missing+=("ADMIN_DID=… in .env (the domain account that writes records)") +[ -f "$USER_HOME/.cloudflared/cert.pem" ] || missing+=("$USER_HOME/.cloudflared/cert.pem (copy from the machine that ran 'cloudflared tunnel login')") +ls "$USER_HOME"/.cloudflared/*.json >/dev/null 2>&1 || missing+=("$USER_HOME/.cloudflared/.json (copy it too)") -for unit in $SERVICES; do - cp "$APP/deploy/$unit.service" /etc/systemd/system/ - systemctl enable "$unit" +# ---------------------------------------------------------------- services + +step "services" + +for unit in "${UNITS[@]}"; do + sed -e "s|/opt/aligned.click|$REPO|g" \ + -e "s|User=aligned|User=$SERVICE_USER|g" \ + -e "s|Group=aligned|Group=$SERVICE_USER|g" \ + -e "s|/usr/bin/node|$NODE|g" \ + -e "s|/usr/local/bin/cloudflared|$CLOUDFLARED|g" \ + "$REPO/deploy/$unit.service" > "/etc/systemd/system/$unit.service" + echo " /etc/systemd/system/$unit.service" done -# Pick up the freshly-copied units (their [Install] sections and hardening) -# before anyone starts them. systemctl daemon-reload -echo "services installed — start with:" -echo " systemctl start aligned-oauth" -echo " systemctl start aligned-app aligned-feedgen" -echo " systemctl start aligned-proxy" -echo " systemctl start aligned-ingest" +if [ ${#missing[@]} -gt 0 ]; then + # Enabled so they start at boot once the missing pieces arrive, but not + # started now — a service that comes up and immediately fails teaches you + # nothing except to distrust the status output. + systemctl enable "${UNITS[@]}" >/dev/null 2>&1 + step "not started — these are missing:" + for m in "${missing[@]}"; do red " $m"; done + echo + echo "Add them, then: sudo systemctl start ${UNITS[*]}" + exit 1 +fi + +systemctl enable --now "${UNITS[@]}" >/dev/null 2>&1 +sleep 4 + +# ---------------------------------------------------------------- report + +step "status" + +for unit in "${UNITS[@]}"; do + state=$(systemctl show -p ActiveState "$unit" | cut -d= -f2) + printf ' %-24s %s\n' "$unit" "$state" +done +echo +green "installed — open:" +echo " https://aligned.click" echo -echo "tunnel: ensure ~/.cloudflared/cert.pem exists, then run:" -echo " cloudflared tunnel --config $APP/deploy/tunnel.yml run" +echo "log tail: journalctl -u aligned-app -f" \ No newline at end of file diff --git a/deploy/tunnel.yml b/deploy/tunnel.yml index c486a63..d93f475 100644 --- a/deploy/tunnel.yml +++ b/deploy/tunnel.yml @@ -1,4 +1,4 @@ -# Cloudflare Tunnel: how aligned.click reaches this machine. +# Cloudflare Tunnel: how aligned.click and agent.aligned.click reach this machine. # # Copy to ~/.cloudflared/config.yml, or run with # `cloudflared tunnel --config deploy/tunnel.yml run`. @@ -7,12 +7,13 @@ # Cloudflare and requests come back down it, which is why this works behind a # home router with nothing forwarded. # -# **The ingress points at the auth proxy, and must never point anywhere else.** +# **The ingress points at the auth proxies, and must never point anywhere else.** # The app, the feed server and the OAuth sidecar all bind 127.0.0.1 and know # nothing about identity; the proxy is the thing that maps a cookie to a DID # and routes by path. A tunnel to the app directly would serve the product to # the internet with no login at all; a tunnel to the sidecar would publish the -# credentials. +# credentials. agent.aligned.click is the opencode agent's own proxy, on a +# different port so both products can share the box. # # The catch-all 404 matters too: without it, a hostname pointed at this tunnel # by mistake would be served the proxy rather than refused. @@ -30,4 +31,6 @@ originRequest: ingress: - hostname: aligned.click service: http://127.0.0.1:8778 + - hostname: agent.aligned.click + service: http://127.0.0.1:8779 - service: http_status:404 \ No newline at end of file diff --git a/feed/store.py b/feed/store.py index b51ee64..201ed40 100644 --- a/feed/store.py +++ b/feed/store.py @@ -1,8 +1,11 @@ """The aligned.click store — the single interface between activities. -private/lancedb (gitignored; the repo's one non-stdlib dependency besides the -venv itself, see requirements.txt) holds the four tables everything else -reads and writes through here: +private/store.db (gitignored) is a SQLite database holding the tables everything +else reads and writes through here. Vector search is computed in-process with +numpy over the stored float32 embeddings — the pool is small (thousands of +posts, 2560-dim vectors), so brute-force cosine search is milliseconds and needs +no native library that fails on older CPUs. (LanceDB, the original backend, +ships AVX2-only wheels and crashes on this deploy's Pentium G4400T.) - **posts** — the pool: every post any keyword ever retrieved (firehose match or backfill search), embedded and deduped by at:// URI. The grade (0-10) is @@ -18,25 +21,28 @@ reads and writes through here: judge says yes (feed/fit.py). - **assignments** — the membership record: (uri, topic) pairs the fit judge decided, fit or not. +- **exemplars** — the topic's region anchor: realistic posts the LLM wrote at + processing time, embedded like the pool (feed/topics.exemplarize). +- **votes** — the +1 cache; the truth is a `click.aligned.feed.vote` record in + the voter's repo. The criteria is embedded and cosine-searched against posts (topic creation, backfill) and against topics (per-post assignment at add time). Distance is -the LanceDB cosine distance (1 - cosine similarity); a post is "within -threshold" when its distance to the topic is at most the topic's threshold. +cosine distance (1 - cosine similarity); a post is "within threshold" when its +distance to the topic is at most the topic's threshold. """ import json +import re +import sqlite3 import threading import time from pathlib import Path -import lancedb -import pyarrow as pa - -from shared.embed import EMBED_DIM +import numpy as np ROOT = Path(__file__).parent -DB_PATH = ROOT.parent / "private" / "lancedb" +DB_PATH = ROOT.parent / "private" / "store.db" _KEYWORDS = "keywords" _POSTS = "posts" @@ -57,198 +63,246 @@ DEFAULT_TOPIC_DISTANCE = float( # so changing this never requires re-judging. DEFAULT_FIT_FLOOR = int(__import__("os").environ.get("FIT_FLOOR", "5")) -# LanceDB vector searches default to 10 results when no `.limit()` is given. -# These region searches are candidates to be *filtered by distance after* the -# limit, so the pre-filter must be generous — otherwise a region is silently -# cut off at the 10 nearest posts per anchor. 1000 is well past any realistic -# region while still a cheap single-shot search. +# Vector searches pull this many nearest candidates before the distance filter, +# so a dense region is not silently cut off at the first few nearest. 1000 is +# well past any realistic region while still a cheap single-shot numpy search. VECTOR_SEARCH_LIMIT = int(__import__("os").environ.get("VECTOR_SEARCH_LIMIT", "1000")) - -def _vector(): - return pa.list_(pa.float32(), EMBED_DIM) - +# Column layouts: (name, sqlite type, kind) where kind is str/int/bool/float/vec. +# `vec` columns are float32 arrays stored as BLOBs and decoded to lists. +_TABLES = { + _KEYWORDS: [ + ("keyword", "TEXT", "str"), ("embedding", "BLOB", "vec"), + ("status", "TEXT", "str"), ("post_count", "INTEGER", "int"), + ("last_seen", "TEXT", "str"), ("last_indexed", "TEXT", "str"), + ("provenance", "TEXT", "str"), ("created", "TEXT", "str"), + ], + _POSTS: [ + ("uri", "TEXT", "str"), ("handle", "TEXT", "str"), + ("did", "TEXT", "str"), ("displayName", "TEXT", "str"), + ("text", "TEXT", "str"), ("embedding", "BLOB", "vec"), + ("source_keyword", "TEXT", "str"), ("createdAt", "TEXT", "str"), + ("replyTo", "TEXT", "str"), ("media", "TEXT", "str"), + ("likeCount", "INTEGER", "int"), ("replyCount", "INTEGER", "int"), + ("repostCount", "INTEGER", "int"), ("grade", "INTEGER", "int"), + ("graded", "INTEGER", "bool"), ("why", "TEXT", "str"), + ("first_seen", "TEXT", "str"), ("last_seen", "TEXT", "str"), + ], + _TOPICS: [ + ("rkey", "TEXT", "str"), ("did", "TEXT", "str"), + ("text", "TEXT", "str"), ("embedding", "BLOB", "vec"), + ("distance", "REAL", "float"), ("status", "TEXT", "str"), + ("processed", "INTEGER", "bool"), ("created", "TEXT", "str"), + ("last_assigned", "TEXT", "str"), + ], + _ASSIGNMENTS: [ + ("uri", "TEXT", "str"), ("topic", "TEXT", "str"), + ("fit", "INTEGER", "bool"), ("score", "INTEGER", "int"), + ("why", "TEXT", "str"), ("judged", "INTEGER", "bool"), + ("judgedAt", "TEXT", "str"), + ], + _EXEMPLARS: [ + ("topic", "TEXT", "str"), ("text", "TEXT", "str"), + ("embedding", "BLOB", "vec"), + ], + _VOTES: [ + ("uri", "TEXT", "str"), ("did", "TEXT", "str"), + ("created", "TEXT", "str"), + ], +} + +# Primary keys, for upserts and dedup. +_KEYS = { + _KEYWORDS: ["keyword"], + _POSTS: ["uri"], + _TOPICS: ["rkey"], + _ASSIGNMENTS: ["uri", "topic"], + _EXEMPLARS: ["topic", "text"], + _VOTES: ["uri", "did"], +} _db = None -_tables: dict[str, object] = {} -_tables_at: float = 0.0 +_db_lock = threading.RLock() +# name -> (loaded_at, rows, {key-tuple: row-index}) +_tables: dict[str, tuple[float, list[dict], dict]] = {} _TABLE_TTL = float(__import__("os").environ.get("STORE_TABLE_TTL", "15")) -def _conn(): +def _conn() -> sqlite3.Connection: global _db if _db is None: - _db = lancedb.connect(str(DB_PATH)) + _db = sqlite3.connect(str(DB_PATH), check_same_thread=False) + _db.row_factory = sqlite3.Row + _db.execute("PRAGMA journal_mode=WAL") + _db.execute("PRAGMA busy_timeout=10000") + _db.execute("PRAGMA synchronous=NORMAL") return _db -def _table(name: str): - # The cached handle is only valid briefly: another process (the worker) - # writes to the same store constantly, and LanceDB snapshots the table at - # first open, so a long-lived app/feedgen would otherwise serve frozen data - # until restart. Drop the cache on a short timer so the next open_table - # re-reads the latest version. (REVIEW effectivity 3.) - global _tables_at - if time.time() - _tables_at >= _TABLE_TTL: - _tables.clear() - _tables_at = time.time() - if name not in _tables: - _tables[name] = _conn().open_table(name) - return _tables[name] +def _cols(name: str) -> list[str]: + return [c[0] for c in _TABLES[name]] + + +def _decode(kind: str, raw): + if raw is None: + return None + if kind == "vec": + return np.frombuffer(raw, dtype=np.float32) + if kind == "int": + return int(raw) if raw is not None else 0 + if kind == "bool": + return bool(raw) if raw is not None else False + if kind == "float": + return float(raw) if raw is not None else 0.0 + return raw + + +def _encode(kind: str, value): + if kind == "vec" and value is not None: + return np.asarray(value, dtype=np.float32).tobytes() + if kind == "bool": + return 1 if value else 0 + return value def _names() -> set[str]: - """The existing table names. `list_tables()` returns a response object in - this lancedb version, so reach into `.tables` rather than `in`-checking it.""" - try: - resp = _conn().list_tables() - names = resp.tables if hasattr(resp, "tables") else list(resp) - except Exception: # noqa: BLE001 — older/newer lancedb shapes - names = _conn().table_names() - return set(names) + rows = _conn().execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") + return {r[0] for r in rows} def ensure() -> None: - """Create the four tables on first use. Idempotent afterwards.""" - conn = _conn() - if _KEYWORDS not in _names(): - t = conn.create_table(_KEYWORDS, schema=pa.schema([ - pa.field("keyword", pa.string()), - pa.field("embedding", _vector()), - pa.field("status", pa.string()), - pa.field("post_count", pa.int64()), - pa.field("last_seen", pa.string()), - pa.field("last_indexed", pa.string()), - pa.field("provenance", pa.string()), - pa.field("created", pa.string()), - ])) - _tables[_KEYWORDS] = t - if _POSTS not in _names(): - t = conn.create_table(_POSTS, schema=pa.schema([ - pa.field("uri", pa.string()), - pa.field("handle", pa.string()), - pa.field("did", pa.string()), - pa.field("displayName", pa.string()), - pa.field("text", pa.string()), - pa.field("embedding", _vector()), - pa.field("source_keyword", pa.string()), - pa.field("createdAt", pa.string()), - pa.field("replyTo", pa.string()), - pa.field("media", pa.string()), - pa.field("likeCount", pa.int64()), - pa.field("replyCount", pa.int64()), - pa.field("repostCount", pa.int64()), - pa.field("grade", pa.int8()), - pa.field("graded", pa.bool_()), - pa.field("why", pa.string()), - pa.field("first_seen", pa.string()), - pa.field("last_seen", pa.string()), - ])) - _tables[_POSTS] = t - if _TOPICS not in _names(): - t = conn.create_table(_TOPICS, schema=pa.schema([ - pa.field("rkey", pa.string()), - pa.field("did", pa.string()), - pa.field("text", pa.string()), - pa.field("embedding", _vector()), - pa.field("distance", pa.float32()), - pa.field("status", pa.string()), - pa.field("processed", pa.bool_()), - pa.field("created", pa.string()), - pa.field("last_assigned", pa.string()), - ])) - _tables[_TOPICS] = t - if _ASSIGNMENTS not in _names(): - t = conn.create_table(_ASSIGNMENTS, schema=pa.schema([ - pa.field("uri", pa.string()), - pa.field("topic", pa.string()), - pa.field("fit", pa.bool_()), - pa.field("score", pa.int8()), - pa.field("why", pa.string()), - pa.field("judged", pa.bool_()), - pa.field("judgedAt", pa.string()), - ])) - _tables[_ASSIGNMENTS] = t - if _EXEMPLARS not in _names(): - t = conn.create_table(_EXEMPLARS, schema=pa.schema([ - pa.field("topic", pa.string()), - pa.field("text", pa.string()), - pa.field("embedding", _vector()), - ])) - _tables[_EXEMPLARS] = t - if _VOTES not in _names(): - t = conn.create_table(_VOTES, schema=pa.schema([ - pa.field("uri", pa.string()), - pa.field("did", pa.string()), - pa.field("created", pa.string()), - ])) - _tables[_VOTES] = t + """Create the tables on first use. Idempotent afterwards.""" + with _db_lock: + conn = _conn() + existing = _names() + for name, cols in _TABLES.items(): + if name in existing: + continue + colsql = ", ".join( + f'"{c}" {t}' for c, t, _ in cols) + keys = _KEYS[name] + if len(keys) == 1: + colsql += f', PRIMARY KEY ("{keys[0]}")' + else: + colsql += f', PRIMARY KEY ({", ".join(f"\"{k}\"" for k in keys)})' + conn.execute(f'CREATE TABLE "{name}" ({colsql})') + conn.commit() _migrate() +_migrating = False + + def _migrate() -> None: """Add columns the running code expects but older stores lack. Existing - rows get the default, so nothing is re-embedded.""" - expected = { - "replyTo": pa.string(), - "grade": pa.int8(), - "displayName": pa.string(), - "media": pa.string(), - "likeCount": pa.int64(), - "replyCount": pa.int64(), - "repostCount": pa.int64(), - "graded": pa.bool_(), - } - try: - existing = {f.name for f in _table(_POSTS).schema} - missing = [pa.field(name, typ) for name, typ in expected.items() - if name not in existing] - if missing: - _table(_POSTS).add_columns(missing) - _tables.pop(_POSTS, None) - except Exception: # noqa: BLE001 — a store that cannot migrate still works - pass - try: - topic_fields = {f.name for f in _table(_TOPICS).schema} - if "processed" not in topic_fields: - _table(_TOPICS).add_columns([pa.field("processed", pa.bool_())]) - _tables.pop(_TOPICS, None) - except Exception: # noqa: BLE001 - pass + rows get the default, so nothing is re-embedded. Guarded against re-entry + because it reads rows via _rows, which calls ensure() -> _migrate().""" + global _migrating + if _migrating: + return + _migrating = True try: - existing = {f.name for f in _table(_ASSIGNMENTS).schema} - if "score" not in existing: - # Old judgements are binary: a stored fit was a yes. Backfill them - # above the floor so they keep appearing; the judge now writes a - # real 0-10 score. - _table(_ASSIGNMENTS).add_columns([pa.field("score", pa.int8())]) - _tables.pop(_ASSIGNMENTS, None) - table = _table(_ASSIGNMENTS) - rows = table.search().to_arrow().to_pylist() + with _db_lock: + conn = _conn() + for name, cols in _TABLES.items(): + cols_here = {r[1] for r in conn.execute(f'PRAGMA table_info("{name}")')} + for c, t, _ in cols: + if c not in cols_here: + conn.execute(f'ALTER TABLE "{name}" ADD COLUMN "{c}" {t}') + conn.commit() + _tables.clear() + try: + rows = _rows(_ASSIGNMENTS) for r in rows: - r["score"] = 6 if r.get("fit") else 0 - if rows: - table.merge_insert(["uri", "topic"]) \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute(rows) - except Exception: # noqa: BLE001 — a store that cannot migrate still works - pass + if r.get("judged") and not r.get("score"): + # Old judgements are binary: a stored fit was a yes. Backfill + # them above the floor so they keep appearing; the judge now + # writes a real 0-10 score. + r["score"] = 6 if r.get("fit") else 0 + _upsert(_ASSIGNMENTS, r) + except Exception: # noqa: BLE001 — a store that cannot migrate still works + pass + finally: + _migrating = False def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) +def _load(name: str) -> tuple[list[dict], dict]: + """All rows of a table as plain dicts, plus a primary-key index, cached with + a short TTL so a long-lived process re-reads other processes' writes.""" + now = time.time() + cached = _tables.get(name) + if cached and now - cached[0] < _TABLE_TTL: + return cached[1], cached[2] + with _db_lock: + cols = _cols(name) + kinds = {c: k for c, _, k in _TABLES[name]} + cur = _conn().execute(f'SELECT * FROM "{name}"') + rows = [] + index: dict = {} + for raw in cur.fetchall(): + row = {} + for i, c in enumerate(cols): + row[c] = _decode(kinds[c], raw[i]) + index[tuple(row[k] for k in _KEYS[name])] = len(rows) + rows.append(row) + _tables[name] = (now, rows, index) + return rows, index + + +def _invalidate(name: str) -> None: + _tables.pop(name, None) + + +def _match(row: dict, where: str | None) -> bool: + """Evaluate the small SQL-where dialect the callers build. The forms used + are all equality on a column, `>=` on a number, `IN (list)`, boolean + equality, and AND-combinations — no joins, no OR, no subqueries. Evaluated + here in Python rather than handed to SQLite, which both fixes the + SQL-injection class (reviewed: the where strings are built over user input) + and keeps the filter semantics identical to the old LanceDB backend.""" + if not where: + return True + for clause in where.split(" AND "): + clause = clause.strip() + m = re.match(r"^(\w+)\s*=\s*'([^']*)'$", clause) + if m: + if str(row.get(m.group(1), "")) != m.group(2): + return False + continue + m = re.match(r"^(\w+)\s*=\s*(true|false)$", clause) + if m: + want = m.group(2) == "true" + if bool(row.get(m.group(1))) != want: + return False + continue + m = re.match(r"^(\w+)\s*>=\s*(-?\d+)$", clause) + if m: + if (row.get(m.group(1)) or 0) < int(m.group(2)): + return False + continue + m = re.match(r"^(\w+)\s+IN\s*\(([^)]*)\)$", clause) + if m: + items = {x.strip().strip("'") for x in m.group(2).split(",")} + if str(row.get(m.group(1))) not in items: + return False + continue + raise ValueError(f"unsupported where clause: {clause}") + return True + + def _rows(table: str, where: str | None = None, limit: int | None = None) -> list[dict]: """All rows of a table (optionally filtered), as plain dicts.""" ensure() - q = _table(table).search() - if where: - q = q.where(where) + rows, _ = _load(table) + rows = [r for r in rows if _match(r, where)] if limit: - q = q.limit(limit) - return q.to_arrow().to_pylist() + return rows[:limit] + return rows def _get(table: str, key_col: str, key: str) -> dict | None: @@ -256,6 +310,75 @@ def _get(table: str, key_col: str, key: str) -> dict | None: return rows[0] if rows else None +def _upsert(name: str, row: dict, merge: list[str] | None = None) -> None: + """Insert or update one row. With `merge`, only those columns are overwritten + on an existing row; the rest keep their stored value. The primary key decides + match.""" + with _db_lock: + keys = _KEYS[name] + conn = _conn() + cols = _cols(name) + kinds = {c: k for c, _, k in _TABLES[name]} + rows, index = _load(name) + key_tuple = tuple(row[k] for k in keys) + i = index.get(key_tuple) + if i is not None: + existing = rows[i] + if merge: + for c in merge: + if c in row: + existing[c] = row[c] + else: + for c in row: + existing[c] = row[c] + row = existing + vals = {c: _encode(kinds[c], row.get(c)) for c in cols} + colsql = ", ".join(f'"{c}"' for c in cols) + placeholders = ", ".join("?" for _ in cols) + updates = ", ".join(f'"{c}" = excluded."{c}"' for c in cols if c not in keys) + sql = (f'INSERT INTO "{name}" ({colsql}) VALUES ({placeholders}) ' + f'ON CONFLICT({", ".join(f"\"{k}\"" for k in keys)}) ' + f'DO UPDATE SET {updates}') + conn.execute(sql, [vals[c] for c in cols]) + conn.commit() + # Keep the cached rows consistent in place so a burst of upserts does + # not reload the whole table on every write (the migration and the + # firehose both write many rows in sequence). + if i is not None: + for c in cols: + if c in row: + rows[i][c] = row[c] + else: + rows.append(row) + index[key_tuple] = len(rows) - 1 + + +def _vector_search(name: str, vec: list[float], limit: int, + where: str | None = None) -> list[dict]: + """The `limit` rows nearest to `vec` under cosine distance, each with + `_distance` set. An optional where filter narrows the candidate set first.""" + rows, _ = _load(name) + if where: + rows = [r for r in rows if _match(r, where)] + if not rows: + return [] + mat = np.array([r["embedding"] for r in rows], dtype=np.float32) + v = np.asarray(vec, dtype=np.float32) + norms = np.linalg.norm(mat, axis=1) + vnorm = np.linalg.norm(v) + denom = norms * vnorm + denom = np.where(denom == 0, 1.0, denom) + sim = (mat @ v) / denom + dist = 1.0 - sim + order = np.argsort(dist) + out = [] + for i in order[:limit]: + r = dict(rows[i]) + r["_distance"] = float(dist[i]) + out.append(r) + return out + + # --- progress (the per-topic status queue) ------------------------------------ # # A topic's processing emits statuses — "searching \"repair cafe\"…", @@ -315,28 +438,24 @@ def add_keyword(keyword: str, embedding: list[float], provenance: str, last_indexed: str = "") -> None: """Insert the keyword, or update it in place (one entry per keyword, ever).""" ensure() - _table(_KEYWORDS).merge_insert("keyword") \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute([{ - "keyword": keyword, "embedding": embedding, "status": status, - "post_count": post_count, "last_seen": "", "last_indexed": last_indexed, - "provenance": provenance, "created": _now(), - }]) + _upsert(_KEYWORDS, { + "keyword": keyword, "embedding": embedding, "status": status, + "post_count": post_count, "last_seen": "", "last_indexed": last_indexed, + "provenance": provenance, "created": _now(), + }) def touch_keyword(keyword: str, post_count: int | None = None) -> None: """A keyword observed matching posts: bump last_seen and (optionally) the volume seen this window. The aliveness signal the pruner reads.""" ensure() - rows = _rows(_KEYWORDS, f"keyword = '{keyword}'", 1) - if not rows: + row = _get(_KEYWORDS, "keyword", keyword) + if not row: return - row = dict(rows[0]) row["last_seen"] = _now() if post_count is not None: row["post_count"] = post_count - _table(_KEYWORDS).merge_insert("keyword").when_matched_update_all().execute([row]) + _upsert(_KEYWORDS, row) def update_keyword(keyword: str, status: str | None = None, @@ -344,17 +463,16 @@ def update_keyword(keyword: str, status: str | None = None, last_indexed: str | None = None) -> None: """Touch selected fields of one keyword. No-op when it does not exist.""" ensure() - rows = _rows(_KEYWORDS, f"keyword = '{keyword}'", 1) - if not rows: + row = _get(_KEYWORDS, "keyword", keyword) + if not row: return - row = dict(rows[0]) if status is not None: row["status"] = status if post_count is not None: row["post_count"] = post_count if last_indexed is not None: row["last_indexed"] = last_indexed - _table(_KEYWORDS).merge_insert("keyword").when_matched_update_all().execute([row]) + _upsert(_KEYWORDS, row) def get_keyword(keyword: str) -> dict | None: @@ -372,10 +490,8 @@ def similar_keywords(vec: list[float], k: int = 10) -> list[dict]: the harvest call can see what is already known — including what was disqualified and why it must not be re-proposed.""" ensure() - rows = _table(_KEYWORDS).search(vec).metric("cosine").limit(k) \ - .to_arrow().to_pylist() out = [] - for r in rows: + for r in _vector_search(_KEYWORDS, vec, k): out.append({ "keyword": r["keyword"], "status": r["status"], "post_count": r["post_count"], "last_seen": r.get("last_seen", ""), @@ -395,7 +511,6 @@ def keyword_counts() -> dict[str, int]: # --- posts (the pool) --------------------------------------------------------- - # Columns add_posts is allowed to merge. grade/graded/why are owned by # mark_graded and never touched by pool writes — a firehose or backfill re-see # must not reset a grade. first_seen is kept once set. @@ -417,30 +532,21 @@ def add_posts(rows: list[dict], update: list[str] | None = None) -> None: grade/graded/why are never merged here — mark_graded owns them, so a re-see cannot reset a stored grade. `update` narrows the merge for firehose rows (no handle/displayName), so a re-see cannot blank a handle the - backfill already filled. This lancedb version only merges update_all, so - an existing row is read, overlaid with the allowed columns, and rewritten. + backfill already filled. """ if not rows: return ensure() - table = _table(_POSTS) - cols = update or _POST_MERGE - batch: list[dict] = [] + merge = update or _POST_MERGE for row in rows: - existing = table.search().where(f"uri = '{row['uri']}'").limit(1) \ - .to_arrow().to_pylist() + existing = _get(_POSTS, "uri", row["uri"]) if existing: - merged = dict(existing[0]) - for col in cols: + for col in merge: if col in row: - merged[col] = row[col] - batch.append(merged) + existing[col] = row[col] + _upsert(_POSTS, existing) else: - batch.append(row) - table.merge_insert("uri") \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute(batch) + _upsert(_POSTS, row) def get_post(uri: str) -> dict | None: @@ -453,9 +559,8 @@ def posts_within(vec: list[float], distance: float, limit: int | None = None) -> The search pulls a generous `VECTOR_SEARCH_LIMIT` before the distance filter so a dense region is not cut off at the first N nearest.""" ensure() - rows = _table(_POSTS).search(vec).metric("cosine").limit(VECTOR_SEARCH_LIMIT) \ - .to_arrow().to_pylist() - out = [r for r in rows if r.get("_distance", 1) <= distance] + out = [r for r in _vector_search(_POSTS, vec, VECTOR_SEARCH_LIMIT) + if r["_distance"] <= distance] for r in out: r.pop("embedding", None) if limit: @@ -468,8 +573,7 @@ def similar_posts(vec: list[float], k: int = 20, """The k nearest embedded posts to a criteria embedding. Used by backfill and topic seeding when a threshold alone would starve the pool.""" ensure() - rows = _table(_POSTS).search(vec).metric("cosine").limit(max(k * 3, 60)) \ - .to_arrow().to_pylist() + rows = _vector_search(_POSTS, vec, max(k * 3, 60)) for r in rows: r.pop("embedding", None) if not exclude_uris: @@ -485,19 +589,17 @@ def mark_graded(grades: list[tuple]) -> None: if not grades: return ensure() - table = _table(_POSTS) for uri, grade, why in grades: - rows = table.search().where(f"uri = '{uri}'").limit(1).to_arrow().to_pylist() - if not rows: + row = _get(_POSTS, "uri", uri) + if not row: continue - row = dict(rows[0]) try: row["grade"] = int(grade) except (TypeError, ValueError): row["grade"] = 0 row["graded"] = True row["why"] = str(why or "")[:200] - table.merge_insert("uri").when_matched_update_all().execute([row]) + _upsert(_POSTS, row) def post_counts() -> dict: @@ -518,27 +620,23 @@ def add_topic(rkey: str, did: str, text: str, embedding: list[float], A fresh topic is unprocessed: the worker harvests its keywords and seeds its region in the background (feed/topics.process_topic).""" ensure() - _table(_TOPICS).merge_insert("rkey") \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute([{ - "rkey": rkey, "did": did, "text": text, "embedding": embedding, - "distance": distance if distance is not None else DEFAULT_TOPIC_DISTANCE, - "status": "active", "processed": False, "created": _now(), - "last_assigned": "", - }]) + _upsert(_TOPICS, { + "rkey": rkey, "did": did, "text": text, "embedding": embedding, + "distance": distance if distance is not None else DEFAULT_TOPIC_DISTANCE, + "status": "active", "processed": False, "created": _now(), + "last_assigned": "", + }) def mark_topic_processed(rkey: str) -> None: """Mark a topic's harvest/index/seed pass done; later pass_topic runs stay cheap (idempotent by assignment).""" ensure() - rows = _rows(_TOPICS, f"rkey = '{rkey}'", 1) - if not rows: + row = _get(_TOPICS, "rkey", rkey) + if not row: return - row = dict(rows[0]) row["processed"] = True - _table(_TOPICS).merge_insert("rkey").when_matched_update_all().execute([row]) + _upsert(_TOPICS, row) def unprocessed_topics() -> list[dict]: @@ -559,7 +657,7 @@ def rename_topic(rkey: str, text: str, embedding: list[float]) -> None: return row["text"] = text row["embedding"] = embedding - _table(_TOPICS).merge_insert("rkey").when_matched_update_all().execute([row]) + _upsert(_TOPICS, row) def delete_topic(rkey: str) -> None: @@ -567,9 +665,14 @@ def delete_topic(rkey: str) -> None: exemplars, and its progress queue. Votes on posts survive — a +1 is the voter's record, not the topic's.""" ensure() - _table(_TOPICS).delete(f"rkey = '{rkey}'") - _table(_ASSIGNMENTS).delete(f"topic = '{rkey}'") - _table(_EXEMPLARS).delete(f"topic = '{rkey}'") + with _db_lock: + conn = _conn() + for name in (_TOPICS, _ASSIGNMENTS, _EXEMPLARS): + conn.execute(f'DELETE FROM "{name}" WHERE rkey = ?' if name == _TOPICS + else f'DELETE FROM "{name}" WHERE topic = ?', (rkey,)) + conn.commit() + for name in (_TOPICS, _ASSIGNMENTS, _EXEMPLARS): + _invalidate(name) clear_progress(rkey) @@ -587,11 +690,9 @@ def topics_near(vec: list[float], limit: int | None = None) -> list[dict]: nearest first. The embedding half of "does this post belong in a topic". Pulls `VECTOR_SEARCH_LIMIT` before the distance filter, then trims.""" ensure() - rows = _table(_TOPICS).search(vec).metric("cosine").limit(VECTOR_SEARCH_LIMIT) \ - .to_arrow().to_pylist() out = [] - for r in rows: - if r.get("_distance", 1) <= float(r.get("distance", DEFAULT_TOPIC_DISTANCE)): + for r in _vector_search(_TOPICS, vec, VECTOR_SEARCH_LIMIT): + if r["_distance"] <= float(r.get("distance", DEFAULT_TOPIC_DISTANCE)): out.append({"rkey": r["rkey"], "did": r["did"], "text": r["text"], "distance": r.get("distance"), "_distance": r.get("_distance")}) if limit: @@ -617,17 +718,18 @@ def add_exemplars(topic: str, items: list[dict]) -> None: clear_exemplars(topic) if not items: return - rows = [{"topic": topic, "text": it["text"], "embedding": it["embedding"]} - for it in items] - _table(_EXEMPLARS).merge_insert(["topic", "text"]) \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute(rows) + for it in items: + _upsert(_EXEMPLARS, {"topic": topic, "text": it["text"], + "embedding": it["embedding"]}) def clear_exemplars(topic: str) -> None: ensure() - _table(_EXEMPLARS).delete(f"topic = '{topic}'") + with _db_lock: + conn = _conn() + conn.execute(f'DELETE FROM "{_EXEMPLARS}" WHERE topic = ?', (topic,)) + conn.commit() + _invalidate(_EXEMPLARS) def exemplars_for(topic: str) -> list[dict]: @@ -645,10 +747,8 @@ def posts_within_exemplars(vecs: list[list[float]], distance: float, ensure() best: dict[str, dict] = {} for v in vecs: - rows = _table(_POSTS).search(v).metric("cosine").limit(VECTOR_SEARCH_LIMIT) \ - .to_arrow().to_pylist() - for r in rows: - d = r.get("_distance", 1) + for r in _vector_search(_POSTS, v, VECTOR_SEARCH_LIMIT): + d = r["_distance"] if d <= distance and (r["uri"] not in best or d < best[r["uri"]]["_distance"]): r["_distance"] = d @@ -668,14 +768,12 @@ def topics_near_exemplars(vec: list[float], limit: int | None = None) -> list[di `VECTOR_SEARCH_LIMIT` before the distance filter so, as topics multiply, a post is still checked against every region it falls in.""" ensure() - rows = _table(_EXEMPLARS).search(vec).metric("cosine").limit(VECTOR_SEARCH_LIMIT) \ - .to_arrow().to_pylist() best: dict[str, dict] = {} - for r in rows: + for r in _vector_search(_EXEMPLARS, vec, VECTOR_SEARCH_LIMIT): topic = _get(_TOPICS, "rkey", r["topic"]) if not topic or topic.get("status") != "active": continue - d = r.get("_distance", 1) + d = r["_distance"] if d <= float(topic.get("distance", DEFAULT_TOPIC_DISTANCE)): if r["topic"] not in best or d < best[r["topic"]]["_distance"]: best[r["topic"]] = {"rkey": r["topic"], "did": topic.get("did", ""), @@ -701,14 +799,11 @@ def assign(uri: str, topic: str, score: int, why: str) -> None: except (TypeError, ValueError): score = 0 score = max(0, min(10, score)) - _table(_ASSIGNMENTS).merge_insert(["uri", "topic"]) \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute([{ - "uri": uri, "topic": topic, "fit": bool(score >= DEFAULT_FIT_FLOOR), - "score": score, "why": str(why or "")[:200], - "judged": True, "judgedAt": _now(), - }]) + _upsert(_ASSIGNMENTS, { + "uri": uri, "topic": topic, "fit": bool(score >= DEFAULT_FIT_FLOOR), + "score": score, "why": str(why or "")[:200], + "judged": True, "judgedAt": _now(), + }) def assignment_exists(uri: str, topic: str) -> bool: @@ -796,10 +891,7 @@ def main_feed(limit: int = 100, min_grade: int | None = None, def vote(uri: str, did: str) -> None: ensure() - _table(_VOTES).merge_insert(["uri", "did"]) \ - .when_matched_update_all() \ - .when_not_matched_insert_all() \ - .execute([{"uri": uri, "did": did, "created": _now()}]) + _upsert(_VOTES, {"uri": uri, "did": did, "created": _now()}) def vote_counts(uris: list[str]) -> dict[str, int]: diff --git a/requirements.txt b/requirements.txt index 33ea679..6e9d2d7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,9 @@ -# The aligned.click product's only non-stdlib dependencies: LanceDB for the -# embedded store (green-embedding vectors) and a websocket client for Jetstream. -# Everything else — GreenPT calls, atproto search, the servers — is stdlib, -# like the rest of the repo. +# The aligned.click product's only non-stdlib dependencies: numpy for the +# in-process vector search (the store is sqlite3 + numpy — LanceDB's wheels +# require AVX2 and crash on the deploy's Pentium G4400T) and a websocket client +# for Jetstream. Everything else — GreenPT calls, atproto search, the servers — +# is stdlib, like the rest of the repo. # # Bootstrap: python3 -m venv .venv && .venv/bin/python -m pip install -r requirements.txt -lancedb==0.33.0 -pyarrow>=20 +numpy>=1.26 websockets>=13 \ No newline at end of file