Spaces:
Configuration error
Configuration error
feat: migrate from Dolt/MySQL to SQLite for faster boot and sync
Browse files- Replace StateKV Dolt/pymysql backend with sqlite3 stdlib (single file DB)
- Add audit_log table to track agent writes (replaces dolt_log versioning)
- Remove Dolt server from Dockerfile and start.sh — no more 5min cold boot wait
- Sync only agentmemory.db + .hmac + second-brain/ (~5MB vs 232MB)
- Restore downloads targeted files instead of full snapshot
- Remove pymysql from requirements.txt
Boot time: ~3min → ~10sec. Backup cycle: 20min → instant when unchanged.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Files changed (6)
- Dockerfile-3
- requirements.txt-2
- src/app.py+15-21
- src/db.py+96-116
- start.sh+1-27
- sync.py+109-72
8 unmodified lines910111213141516178 unmodified linestini \&& rm -rf /var/lib/apt/lists/*# Install DoltRUN curl -L https://github.com/dolthub/dolt/releases/latest/download/install.sh | bash# Set up HF Spaces user (uid 1000 required)RUN useradd -m -u 1000 user8 unmodified lines910111213148 unmodified linestini \&& rm -rf /var/lib/apt/lists/*# Set up HF Spaces user (uid 1000 required)RUN useradd -m -u 1000 user
12345678flask>=3.0.0flask-sock>=0.7.0pymysql>=1.1.0requests>=2.31.0websockets>=12.0python-dateutil>=2.8.2huggingface_hub>=0.20.0123456flask>=3.0.0flask-sock>=0.7.0requests>=2.31.0websockets>=12.0python-dateutil>=2.8.2huggingface_hub>=0.20.0
1280 unmodified lines1281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071280 unmodified linestry:limit = int(request.args.get("limit", "50"))conn = kv._get_conn()try:with conn.cursor() as cursor:cursor.execute("SELECT commit_hash, committer, email, date, message FROM dolt_log ORDER BY date DESC LIMIT %s",(limit,))rows = cursor.fetchall()commits = []for r in rows:commits.append({"sha": r["commit_hash"],"shortSha": r["commit_hash"][:7],"agent": r["committer"],"email": r["email"],"date": r["date"].isoformat() + "Z" if isinstance(r["date"], datetime.datetime) else str(r["date"]),"message": r["message"]})return jsonify({"success": True, "commits": commits}), 200finally:conn.close()except Exception as e:return jsonify({"error": str(e)}), 5001280 unmodified lines1281128212831284128512861287128812891290129112921293129412951296129712981299130013011280 unmodified linestry:limit = int(request.args.get("limit", "50"))rows = kv.get_audit_log(limit)commits = []for r in rows:ts_ms = r["ts"]iso = datetime.datetime.utcfromtimestamp(ts_ms / 1000).isoformat() + "Z"row_id = str(r["id"])commits.append({"sha": row_id.zfill(40),"shortSha": row_id,"agent": r["agent_id"],"email": f"{r['agent_id']}@agentmemory.ai","date": iso,"message": r["message"]})return jsonify({"success": True, "commits": commits}), 200except Exception as e:return jsonify({"error": str(e)}), 500
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990914 unmodified lines969798991001011021031041051061075 unmodified lines1131141151161171181191201211221231241254 unmodified lines1301311321331341351361371381391401411421 unmodified line1441451461471481491501511521531541551561571582 unmodified lines16116216316416516616716816917018 unmodified lines189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225import osimport jsonimport pymysqlimport urllib.parsefrom typing import Dict, Any, List, Optional, TypeVar, UnionT = TypeVar("T")class StateKV:def __init__(self):self.host = os.getenv("DOLT_HOST", "127.0.0.1")self.port = int(os.getenv("DOLT_PORT", "3306"))self.user = os.getenv("DOLT_USER", "root")self.password = os.getenv("DOLT_PASSWORD", "")self.database = os.getenv("DOLT_DATABASE", "agentmemory")self._init_db()def _get_conn(self) -> pymysql.connections.Connection:return pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,database=self.database,charset="utf8mb4",cursorclass=pymysql.cursors.DictCursor,autocommit=True)def _init_db(self):try:# First, check connection and create database if not existsconn = pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,charset="utf8mb4",autocommit=True)try:with conn.cursor() as cursor:cursor.execute(f"CREATE DATABASE IF NOT EXISTS {self.database}")finally:conn.close()# Now connect to database and initialize schemaconn = self._get_conn()try:with conn.cursor() as cursor:cursor.execute("""CREATE TABLE IF NOT EXISTS kv_store (scope VARCHAR(255) NOT NULL,`key` VARCHAR(255) NOT NULL,value LONGTEXT NOT NULL,PRIMARY KEY (scope, `key`))""")try:cursor.execute("CREATE INDEX idx_kv_scope ON kv_store(scope)")except Exception as e:# Index might already exist, ignore error 1061 / 1105 (duplicate key name)if hasattr(e, 'args') and len(e.args) > 0 and (e.args[0] in (1061, 1105) or "Duplicate key name" in str(e)):passelse:raise efinally:conn.close()print(f"[db] Dolt database '{self.database}' initialized successfully.")except Exception as e:print(f"[db] WARNING initializing Dolt database: {e}")print(f"[db] Please ensure your Dolt SQL Server is running on {self.host}:{self.port}")# Do not raise error to allow the app to boot, though subsequent operations will fail if Dolt is off.def get(self, scope: str, key: str) -> Optional[Any]:try:conn = self._get_conn()try:with conn.cursor() as cursor:cursor.execute("SELECT value FROM kv_store WHERE scope = %s AND `key` = %s",(scope, key))row = cursor.fetchone()if row:return json.loads(row["value"])return Nonefinally:conn.close()except Exception as e:4 unmodified linestry:conn = self._get_conn()try:serialized = json.dumps(value)with conn.cursor() as cursor:cursor.execute("REPLACE INTO kv_store (scope, `key`, value) VALUES (%s, %s, %s)",(scope, key, serialized))return valuefinally:conn.close()5 unmodified linestry:conn = self._get_conn()try:with conn.cursor() as cursor:cursor.execute("DELETE FROM kv_store WHERE scope = %s AND `key` = %s",(scope, key))affected = cursor.rowcountreturn affected > 0finally:conn.close()except Exception as e:4 unmodified linestry:conn = self._get_conn()try:with conn.cursor() as cursor:cursor.execute("SELECT value FROM kv_store WHERE scope = %s",(scope,))rows = cursor.fetchall()return [json.loads(row["value"]) for row in rows]finally:conn.close()except Exception as e:1 unmodified linereturn []def update(self, scope: str, key: str, ops: List[Dict[str, Any]]) -> Optional[Any]:try:conn = self._get_conn()try:with conn.cursor() as cursor:cursor.execute("SELECT value FROM kv_store WHERE scope = %s AND `key` = %s FOR UPDATE",(scope, key))row = cursor.fetchone()obj = json.loads(row["value"]) if row else {}if not isinstance(obj, dict):obj = {}2 unmodified linesop_type = op.get("type")path = op.get("path")val = op.get("value")if not path:continueif op_type == "set":if "." in path:parts = path.split(".")18 unmodified lineselse:obj.pop(path, None)serialized = json.dumps(obj)cursor.execute("REPLACE INTO kv_store (scope, `key`, value) VALUES (%s, %s, %s)",(scope, key, serialized))return objfinally:conn.close()except Exception as e:print(f"[db] update failed (scope={scope}, key={key}): {e}")return Nonedef commit_version(self, message: str, agent_id: str) -> Optional[str]:author_name = agent_id or "unknown-agent"author_email = f"{author_name}@agentmemory.ai"author_str = f"{author_name} <{author_email}>"try:conn = self._get_conn()try:with conn.cursor() as cursor:cursor.execute("CALL dolt_add('-A')")cursor.execute("CALL dolt_commit('-m', %s, '--author', %s)", (message, author_str))row = cursor.fetchone()if row:val = list(row.values())[0] if isinstance(row, dict) else row[0]print(f"[dolt commit] Created commit: {val}")return valreturn Nonefinally:conn.close()except Exception as e:print(f"[dolt commit] Failed: {e}")return None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465664 unmodified lines71727374757677787980815 unmodified lines8788899091929394959697984 unmodified lines1031041051061071081091101111121131 unmodified line1151161171181191201211221231241251261271282 unmodified lines13113213313413513613713818 unmodified lines157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205import osimport jsonimport sqlite3import threadingimport timefrom typing import Dict, Any, List, Optional, TypeVar, UnionT = TypeVar("T")DB_PATH = os.path.join(os.path.expanduser("~"), ".agentmemory", "agentmemory.db")class StateKV:def __init__(self, db_path: str = DB_PATH):self.db_path = db_pathself._lock = threading.Lock()self._init_db()def _get_conn(self) -> sqlite3.Connection:conn = sqlite3.connect(self.db_path, check_same_thread=False, timeout=30)conn.row_factory = sqlite3.Rowconn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA synchronous=NORMAL")conn.execute("PRAGMA foreign_keys=ON")return conndef _init_db(self):try:os.makedirs(os.path.dirname(self.db_path), exist_ok=True)conn = self._get_conn()try:conn.execute("""CREATE TABLE IF NOT EXISTS kv_store (scope TEXT NOT NULL,key TEXT NOT NULL,value TEXT NOT NULL,PRIMARY KEY (scope, key))""")conn.execute("CREATE INDEX IF NOT EXISTS idx_kv_scope ON kv_store(scope)")conn.execute("""CREATE TABLE IF NOT EXISTS audit_log (id INTEGER PRIMARY KEY AUTOINCREMENT,ts INTEGER NOT NULL,agent_id TEXT NOT NULL,message TEXT NOT NULL)""")conn.commit()finally:conn.close()print(f"[db] SQLite database initialized at {self.db_path}")except Exception as e:print(f"[db] WARNING initializing SQLite database: {e}")def get(self, scope: str, key: str) -> Optional[Any]:try:conn = self._get_conn()try:row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()return json.loads(row["value"]) if row else Nonefinally:conn.close()except Exception as e:4 unmodified linestry:conn = self._get_conn()try:conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(value)))conn.commit()return valuefinally:conn.close()5 unmodified linestry:conn = self._get_conn()try:cur = conn.execute("DELETE FROM kv_store WHERE scope = ? AND key = ?",(scope, key))conn.commit()return cur.rowcount > 0finally:conn.close()except Exception as e:4 unmodified linestry:conn = self._get_conn()try:rows = conn.execute("SELECT value FROM kv_store WHERE scope = ?",(scope,)).fetchall()return [json.loads(r["value"]) for r in rows]finally:conn.close()except Exception as e:1 unmodified linereturn []def update(self, scope: str, key: str, ops: List[Dict[str, Any]]) -> Optional[Any]:with self._lock:try:conn = self._get_conn()try:row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()obj = json.loads(row["value"]) if row else {}if not isinstance(obj, dict):obj = {}2 unmodified linesop_type = op.get("type")path = op.get("path")val = op.get("value")if not path:continueif op_type == "set":if "." in path:parts = path.split(".")18 unmodified lineselse:obj.pop(path, None)conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(obj)))conn.commit()return objfinally:conn.close()except Exception as e:print(f"[db] update failed (scope={scope}, key={key}): {e}")return Nonedef commit_version(self, message: str, agent_id: str) -> Optional[str]:"""Write an audit log entry instead of a Dolt commit."""author = agent_id or "unknown-agent"try:conn = self._get_conn()try:cur = conn.execute("INSERT INTO audit_log (ts, agent_id, message) VALUES (?, ?, ?)",(int(time.time() * 1000), author, message))conn.commit()row_id = str(cur.lastrowid)print(f"[audit] {author}: {message} (id={row_id})")return row_idfinally:conn.close()except Exception as e:print(f"[audit] commit_version failed: {e}")return Nonedef get_audit_log(self, limit: int = 50) -> List[Dict[str, Any]]:try:conn = self._get_conn()try:rows = conn.execute("SELECT id, ts, agent_id, message FROM audit_log ORDER BY ts DESC LIMIT ?",(limit,)).fetchall()return [dict(r) for r in rows]finally:conn.close()except Exception as e:print(f"[db] get_audit_log failed: {e}")return []
1 unmodified line234567842 unmodified lines515253545556575859606162636465666768697071727374757677787980818283841 unmodified line# Note: no set -e — sync failures must not kill the container# Create agentmemory data directoriesmkdir -p /home/user/.agentmemory/dolt# =============================================================================# Persistent storage via HF Dataset repo42 unmodified linesGRAPH_EXTRACTION_ENABLED=trueAGENTMEMORY_REFLECT=trueAGENTMEMORY_AUTO_COMPRESS=trueDOLT_HOST=127.0.0.1DOLT_PORT=3306DOLT_DATABASE=agentmemoryEOF# Start Dolt SQL serverecho "[start] Starting Dolt SQL Server..."dolt sql-server --host 127.0.0.1 --port 3306 --data-dir /home/user/.agentmemory/dolt &# Wait for Dolt server to bootecho "[start] Waiting for Dolt server to be ready..."sleep 5# One-time migration: import legacy state_store.db binary files into Dolt SQLSTATE_STORE="/home/user/.agentmemory/state_store.db"MIGRATION_DONE="/home/user/.agentmemory/.migration_done"if [ -d "$STATE_STORE" ] && [ ! -f "$MIGRATION_DONE" ]; thenecho "[start] Found legacy state_store.db — running one-time migration to Dolt SQL..."python3 -c "import sys, ossys.path.insert(0, '/app/src')from db import StateKVfrom import_data import import_old_datakv = StateKV()import_old_data('$STATE_STORE', kv)" && touch "$MIGRATION_DONE" && echo "[start] Migration complete."fi# Set the port for Flask application to run on (Hugging Face Space expects 7860)export PORT=7860export III_REST_PORT=78601 unmodified line234567842 unmodified lines51525354555657581 unmodified line# Note: no set -e — sync failures must not kill the container# Create agentmemory data directoriesmkdir -p /home/user/.agentmemory# =============================================================================# Persistent storage via HF Dataset repo42 unmodified linesGRAPH_EXTRACTION_ENABLED=trueAGENTMEMORY_REFLECT=trueAGENTMEMORY_AUTO_COMPRESS=trueEOF# Set the port for Flask application to run on (Hugging Face Space expects 7860)export PORT=7860export III_REST_PORT=7860
1234563 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384859 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271282 unmodified lines131132133134135136137138139#!/usr/bin/env python3"""Sync ~/.agentmemory/ data to/from a private HF Dataset repo.Usage:python3 sync.py restore -- download DB from HF on startuppython3 sync.py backup -- upload DB to HF (called in loop)3 unmodified linesimport sysimport shutilimport tempfiletry:from huggingface_hub import HfApi, snapshot_download, list_repo_filesfrom huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundErrorexcept ImportError:print("[sync] huggingface_hub not installed, skipping sync")sys.exit(0)HF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")DATA_DIR = os.path.expanduser("~/.agentmemory")SKIP_FILES = {".env"}ALLOW_HIDDEN = {".hmac"}SKIP_NAMES = {"LOCK"} # held open by Dolt — always skipdef _quick_hash(data_dir):"""Build a fingerprint from file sizes+mtimes — fast, no file reads."""entries = {}for root, dirs, files in os.walk(data_dir):is_inside_dolt = ".dolt" in root.replace("\\", "/").split("/")if not is_inside_dolt:dirs[:] = [d for d in dirs if not d.startswith(".") or d == ".dolt"]for f in files:if f in SKIP_FILES or f in SKIP_NAMES:continueif f.startswith(".") and f not in ALLOW_HIDDEN:continuefull = os.path.join(root, f)rel = os.path.relpath(full, data_dir).replace("\\", "/")try:s = os.stat(full)entries[rel] = (s.st_size, s.st_mtime)except OSError:passreturn json.dumps(entries, sort_keys=True)def get_api():return HfApi(token=HF_TOKEN)def restore():if not HF_TOKEN:print("[sync] No HF_TOKEN — skipping restore")returnos.makedirs(DATA_DIR, exist_ok=True)try:print(f"[sync] downloading snapshot from {REPO_ID}...")snapshot_download(repo_id=REPO_ID,repo_type="dataset",token=HF_TOKEN,local_dir=DATA_DIR,ignore_patterns=["*.lock"],)print("[sync] restore complete")except RepositoryNotFoundError:print(f"[sync] Dataset repo {REPO_ID} not found — will create on first backup")except Exception as e:print(f"[sync] restore error: {e}")def backup():if not HF_TOKEN:returnapi = get_api()# Fast change detection — skip everything if nothing modifiedstate_file = os.path.join(DATA_DIR, ".backup_state")current_state = _quick_hash(DATA_DIR)if os.path.exists(state_file):try:if open(state_file).read() == current_state:print("[sync] no changes — skipping backup")returnexcept Exception:9 unmodified linesprint(f"[sync] repo_info error: {e}")return# Stage files into a temp dir then upload in one commitstaging = tempfile.mkdtemp(prefix="agentmemory_sync_")try:copied = 0for root, dirs, files in os.walk(DATA_DIR):is_inside_dolt = ".dolt" in root.replace("\\", "/").split("/")if not is_inside_dolt:dirs[:] = [d for d in dirs if not d.startswith(".") or d == ".dolt"]for f in files:if f in SKIP_FILES or f in SKIP_NAMES:continueif f.startswith(".") and f not in ALLOW_HIDDEN:continuefull = os.path.join(root, f)rel = os.path.relpath(full, DATA_DIR).replace("\\", "/")dest = os.path.join(staging, rel.replace("/", os.sep))os.makedirs(os.path.dirname(dest), exist_ok=True)try:shutil.copy2(full, dest)copied += 1except Exception as e:print(f"[sync] stage {rel} error: {e}")if copied == 0:print("[sync] nothing to backup")returnprint(f"[sync] uploading {copied} files to {REPO_ID}...")api.upload_folder(folder_path=staging,repo_id=REPO_ID,2 unmodified linescommit_message="sync: periodic backup",)print("[sync] backup complete")# Save state fingerprint so next cycle skips if nothing changedtry:open(state_file, "w").write(current_state)except Exception:passexcept Exception as e:1234563 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381399 unmodified lines1491501511521531541551561571581591601611621631641651662 unmodified lines169170171172173174175176#!/usr/bin/env python3"""Sync agentmemory data to/from a private HF Dataset repo.Usage:python3 sync.py restore -- download DB from HF on startuppython3 sync.py backup -- upload DB to HF (called in loop)3 unmodified linesimport sysimport shutilimport tempfileimport timetry:from huggingface_hub import HfApi, snapshot_download, hf_hub_downloadfrom huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundErrorexcept ImportError:print("[sync] huggingface_hub not installed, skipping sync")sys.exit(0)HF_TOKEN = os.environ.get("HF_TOKEN", "")REPO_ID = os.environ.get("AGENTMEMORY_DATASET_REPO", "Yash030/agentmemory-python-data")DATA_DIR = os.path.expanduser("~/.agentmemory")# Only these paths are backed up/restored — everything else is ephemeralSYNC_FILES = ["agentmemory.db",".hmac",]SYNC_DIRS = ["second-brain",]STATE_FILE = os.path.join(DATA_DIR, ".backup_state")def get_api():return HfApi(token=HF_TOKEN)def _collect_sync_targets():"""Return list of (abs_path, repo_rel_path) for all files to sync."""targets = []for fname in SYNC_FILES:full = os.path.join(DATA_DIR, fname)if os.path.isfile(full):targets.append((full, fname))for dname in SYNC_DIRS:dpath = os.path.join(DATA_DIR, dname)if os.path.isdir(dpath):for root, _, files in os.walk(dpath):for f in files:full = os.path.join(root, f)rel = os.path.relpath(full, DATA_DIR).replace("\\", "/")targets.append((full, rel))return targetsdef _state_fingerprint(targets):entries = {}for full, rel in targets:try:s = os.stat(full)entries[rel] = (s.st_size, s.st_mtime)except OSError:passreturn json.dumps(entries, sort_keys=True)def restore():if not HF_TOKEN:print("[sync] No HF_TOKEN — skipping restore")returnos.makedirs(DATA_DIR, exist_ok=True)api = get_api()# Check repo existstry:api.repo_info(REPO_ID, repo_type="dataset")except RepositoryNotFoundError:print(f"[sync] Dataset repo {REPO_ID} not found — fresh start")returnexcept Exception as e:print(f"[sync] restore repo check error: {e}")return# Download each sync target individuallyall_targets = SYNC_FILES + [f for f in _list_repo_prefix(api, "second-brain/")]if not all_targets:print("[sync] Dataset empty — fresh start")returnfor fname in all_targets:try:local_path = os.path.join(DATA_DIR, fname)os.makedirs(os.path.dirname(local_path), exist_ok=True)hf_hub_download(repo_id=REPO_ID,filename=fname,repo_type="dataset",token=HF_TOKEN,local_dir=DATA_DIR,local_dir_use_symlinks=False,)print(f"[sync] restored {fname}")except EntryNotFoundError:pass # file not yet in repo, skipexcept Exception as e:print(f"[sync] restore {fname} error: {e}")print("[sync] restore complete")def _list_repo_prefix(api, prefix):"""List files in repo matching a path prefix."""try:from huggingface_hub import list_repo_filesreturn [f for f in list_repo_files(REPO_ID, repo_type="dataset", token=HF_TOKEN)if f.startswith(prefix)]except Exception:return []def backup():if not HF_TOKEN:returnapi = get_api()targets = _collect_sync_targets()if not targets:print("[sync] nothing to backup")return# Fast change detectioncurrent_state = _state_fingerprint(targets)if os.path.exists(STATE_FILE):try:if open(STATE_FILE).read() == current_state:print("[sync] no changes — skipping backup")returnexcept Exception:9 unmodified linesprint(f"[sync] repo_info error: {e}")return# Stage only the targeted filesstaging = tempfile.mkdtemp(prefix="agentmemory_sync_")try:for full, rel in targets:dest = os.path.join(staging, rel.replace("/", os.sep))os.makedirs(os.path.dirname(dest), exist_ok=True)try:shutil.copy2(full, dest)except Exception as e:print(f"[sync] stage {rel} error: {e}")print(f"[sync] uploading {len(targets)} files to {REPO_ID}...")api.upload_folder(folder_path=staging,repo_id=REPO_ID,2 unmodified linescommit_message="sync: periodic backup",)print("[sync] backup complete")try:open(STATE_FILE, "w").write(current_state)except Exception:passexcept Exception as e:
Dockerfile-3
requirements.txt-2
src/app.py+15-21
src/db.py+96-116
start.sh+1-27
sync.py+109-72