From b9d16718464289c69e625220547d08e5ccdd56d9 Mon Sep 17 00:00:00 2001 From: mikkel Date: Wed, 4 Nov 2026 22:34:55 +0000 Subject: [PATCH 1/2] Retire finished threads after seven days without activity --- README.md | 25 ++++- babel/__main__.py | 9 ++ babel/core.py | 25 ++++- babel/retirement.py | 50 ++++++++++ deploy/agent-babel-retire.service | 22 +++++ deploy/agent-babel-retire.timer | 11 +++ tests/test_message_capacity.py | 6 +- tests/test_retirement.py | 156 ++++++++++++++++++++++++++++++ 8 files changed, 298 insertions(+), 6 deletions(-) create mode 100644 babel/retirement.py create mode 100644 deploy/agent-babel-retire.service create mode 100644 deploy/agent-babel-retire.timer create mode 100644 tests/test_retirement.py diff --git a/README.md b/README.md index 4034ada..24f91b4 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ calls. Babel's broker alone cannot establish that guarantee for a hosted ChatGPT Grok, or Codex receiver. The synthetic wake-claim tests count stub enqueue attempts and explicitly reproduce both remaining external-receiver limitations. -Limits: 16 KiB UTF-8/message, 64 KiB HTTP requests, 30 new messages/sender/minute and a separate 300/owner/minute budget shared by its sessions, 100 hops/thread by default (optional schema 3 per-conversation caps up to 100), 100,000 retained messages, four active MCP subscriptions/recipient and 100 retained subscription identities. Both message budgets use durable rolling 60-second windows; 429 errors identify the exhausted budget. Retries of an existing identical message ID do not consume new-message capacity. Capacity failure closes safely instead of silently deleting dedup history. Review storage usage and arrange operator maintenance/backups; there is no automatic destructive pruning. +Limits: 16 KiB UTF-8/message, 64 KiB HTTP requests, 30 new messages/sender/minute and a separate 300/owner/minute budget shared by its sessions, 100 hops/thread by default (optional schema 3 per-conversation caps up to 100), 100,000 active messages, four active MCP subscriptions/recipient and 100 retained subscription identities. Both message budgets use durable rolling 60-second windows; 429 errors identify the exhausted budget. Retries of an existing identical message ID do not consume new-message capacity. Capacity failure closes safely instead of silently deleting dedup history. Finished threads retire automatically after seven days of inactivity and no longer count toward active capacity. Retired history, message IDs, receipts and audit records remain available; disk capacity still needs monitoring. There is no automatic destructive pruning. Back up online: ```sh @@ -217,3 +217,26 @@ OpenCode can use an account-wide [native wake plugin](docs/opencode-wake.md): new sessions automatically receive their own native mailbox context and wake inside the original runtime, with no per-session service or registration. It requires the documented trusted-backend OpenCode compatibility gate. + + +### Inactive thread retirement + +Run `python -m babel retire --dry-run` to preview, or `python -m babel retire` +to retire eligible threads transactionally. Install an hourly operator timer +for normal maintenance; message admission also sweeps at the active capacity +bound if a scheduled run was missed. This command is private operator +maintenance, not a new public MCP tool. + +A thread is a message root plus all replies. It retires only when every message +is acknowledged or canceled and its latest send, approval, acknowledgment or +cancellation is at least seven days old. New replies protect the entire thread. +Reads, polling, notification delivery and retries do not extend that lifetime. +Drafts and unread messages stay active regardless of age. + +Retirement marks all messages in a thread with `retired_at`. History, receipt +retries, audit records and message-ID deduplication remain intact in SQLite and +backups. Retired messages do not consume the active-message quota. New replies +to a retired thread return 410 with instructions to start a new thread; an exact +retry of an existing message ID still returns its original result. Retirement +is additive within schema 4 and does not remove data. A pre-retirement binary +can read the history but will again count retired records toward its total cap. diff --git a/babel/__main__.py b/babel/__main__.py index 93800a0..12c6fee 100644 --- a/babel/__main__.py +++ b/babel/__main__.py @@ -1,4 +1,5 @@ import argparse +import json import os from .core import AGENTS, BridgeError, Store from .mcp import stdio @@ -18,6 +19,8 @@ def main(): gateway.add_argument("--container", action="store_true", help="Listen on private Docker network") modes.add_parser("wake", help="Run explicitly configured HTTPS notification worker") modes.add_parser("backup", help="Online SQLite backup inside configured bridge data/backups") + retire = modes.add_parser("retire", help="Retire finished threads inactive for seven days; preserve history") + retire.add_argument("--dry-run", action="store_true", help="Preview eligible thread/message counts without retiring") from .enrollment import add_parser add_parser(modes) args = parser.parse_args() @@ -61,6 +64,12 @@ def main(): pass finally: store.close() + elif args.mode == "retire": + store = Store() + try: + print(json.dumps(store.retire_threads(dry_run=args.dry_run)), flush=True) + finally: + store.close() elif args.mode == "backup": store = Store() try: diff --git a/babel/core.py b/babel/core.py index fcd7271..d0a8dec 100644 --- a/babel/core.py +++ b/babel/core.py @@ -18,6 +18,7 @@ RATE_LIMIT = 30 OWNER_RATE_LIMIT = 300 MAX_RETAINED_MESSAGES = 100000 +THREAD_IDLE_SECONDS = 7 * 24 * 60 * 60 ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{7,127}\Z") class BridgeError(Exception): @@ -119,6 +120,8 @@ def __init__(self, path=None): if "gone" not in {row[1] for row in self.db.execute("PRAGMA table_info(subscriptions)")}: self.db.execute("ALTER TABLE subscriptions ADD COLUMN gone INTEGER NOT NULL DEFAULT 0") self.db.execute("CREATE INDEX IF NOT EXISTS owner_rate ON messages(source_owner,created)") + from .retirement import initialize + initialize(self.db) self.db.execute("PRAGMA user_version=4") self.db.commit() if str(self.path) != ":memory:": @@ -198,11 +201,17 @@ def stage(self, source, recipient, text, message_id=None, reply_to=None, provena if expected != actual: raise BridgeError("Message ID already belongs to different content", 409) return {"message": existing, "duplicate": True} - if self.db.execute("SELECT COUNT(*) FROM messages").fetchone()[0] >= MAX_RETAINED_MESSAGES: - raise BridgeError("Bridge message capacity reached; operator maintenance required", 507) + from .retirement import active_count, retire + if active_count(self.db) >= MAX_RETAINED_MESSAGES: + # Reclaim eligible threads even if the scheduled sweep was missed. + retire(self.db, time.time(), THREAD_IDLE_SECONDS) + if active_count(self.db) >= MAX_RETAINED_MESSAGES: + raise BridgeError("Bridge active-message capacity reached; unresolved work requires operator review", 507) hops, root_id = 1, message_id if reply_to: parent = self._row(reply_to) + if parent["retired_at"] is not None: + raise BridgeError("Thread retired after inactivity; start a new thread without reply_to", 410) if parent["status"] not in ("queued", "acknowledged"): raise BridgeError("Replies require an approved parent message", 409) if parent["conversation_id"] != conversation_id: @@ -351,6 +360,18 @@ def message_status(self, message_id, role): raise BridgeError("Bridge message not found", 404) return row + def retire_threads(self, dry_run=False): + from .retirement import retire + if type(dry_run) is not bool: + raise BridgeError("dry_run must be a boolean") + with self.transaction(): + return retire(self.db, time.time(), THREAD_IDLE_SECONDS, dry_run=dry_run) + + def retirement_usage(self): + from .retirement import usage + with self.lock: + return usage(self.db) + def backup(self): if str(self.path) == ":memory:": raise BridgeError("Backup requires a persistent bridge database") diff --git a/babel/retirement.py b/babel/retirement.py new file mode 100644 index 0000000..076867a --- /dev/null +++ b/babel/retirement.py @@ -0,0 +1,50 @@ +"""Retire terminal, inactive threads without deleting history or dedup records. + +Caller holds the Store transaction for sweeps. Replies and sweeps therefore +serialize across processes using SQLite's writer lock. +""" + + +def initialize(db): + columns = {row[1] for row in db.execute("PRAGMA table_info(messages)")} + if "retired_at" not in columns: + db.execute("ALTER TABLE messages ADD COLUMN retired_at REAL") + db.execute("CREATE INDEX IF NOT EXISTS thread_messages ON messages(root_id)") + db.execute("CREATE INDEX IF NOT EXISTS active_messages ON messages(retired_at,seq)") + db.execute("CREATE INDEX IF NOT EXISTS message_activity ON events(message_id,action,created)") + + +def active_count(db): + return db.execute("SELECT COUNT(*) FROM messages WHERE retired_at IS NULL").fetchone()[0] + + +def usage(db): + active = active_count(db) + total = db.execute("SELECT COUNT(*) FROM messages").fetchone()[0] + return {"active_messages": active, "retired_messages": total - active, "total_messages": total} + + +# Read/export/claim/poll activity deliberately does not extend thread lifetime. +# Approval and receipt timestamps live on messages; cancellation is an audit event. +ELIGIBLE = """ + SELECT m.root_id, COUNT(*) AS messages + FROM messages m WHERE m.retired_at IS NULL + GROUP BY m.root_id + HAVING SUM(m.status NOT IN ('acknowledged','canceled')) = 0 + AND MAX(MAX(m.created, COALESCE(m.approved, 0), COALESCE(m.acknowledged, 0), + COALESCE((SELECT MAX(e.created) FROM events e + WHERE e.message_id=m.id AND e.action='canceled'), 0))) <= ? +""" + + +def retire(db, now, idle_seconds, dry_run=False): + cutoff = now - idle_seconds + eligible = db.execute( + "SELECT COUNT(*), COALESCE(SUM(messages),0) FROM (" + ELIGIBLE + ")", + (cutoff,)).fetchone() + if not dry_run and eligible[0]: + db.execute("UPDATE messages SET retired_at=? WHERE retired_at IS NULL " + "AND root_id IN (SELECT root_id FROM (" + ELIGIBLE + "))", (now, cutoff)) + return {"dry_run": dry_run, "idle_days": idle_seconds // 86400, + "inactive_before": cutoff, "eligible_threads": eligible[0], + "eligible_messages": eligible[1], **usage(db)} diff --git a/deploy/agent-babel-retire.service b/deploy/agent-babel-retire.service new file mode 100644 index 0000000..2ecb224 --- /dev/null +++ b/deploy/agent-babel-retire.service @@ -0,0 +1,22 @@ +[Unit] +Description=Retire finished Agent Babel threads after seven inactive days + +[Service] +Type=oneshot +User=agent-babel +Group=agent-babel +WorkingDirectory=/srv/agent-babel +Environment=BABEL_DATA_DIR=/var/lib/agent-babel +ExecStart=/srv/agent-babel/venv/bin/python -m babel retire +TimeoutStartSec=120 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/lib/agent-babel +RestrictAddressFamilies=AF_UNIX +IPAddressDeny=any +CapabilityBoundingSet= +MemoryMax=256M +TasksMax=20 diff --git a/deploy/agent-babel-retire.timer b/deploy/agent-babel-retire.timer new file mode 100644 index 0000000..2aa14d4 --- /dev/null +++ b/deploy/agent-babel-retire.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Check Agent Babel thread retirement hourly + +[Timer] +OnCalendar=hourly +Persistent=true +AccuracySec=1min +Unit=agent-babel-retire.service + +[Install] +WantedBy=timers.target diff --git a/tests/test_message_capacity.py b/tests/test_message_capacity.py index f641a3c..bf4e86c 100644 --- a/tests/test_message_capacity.py +++ b/tests/test_message_capacity.py @@ -11,14 +11,14 @@ def test_old_limit_and_exact_new_limit_preserve_history_across_restart(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / 'bridge.sqlite3' store = Store(path) - # Historical rows are outside rolling rate windows. Keep mixed states - # to cover both undelivered work and acknowledged history. + # Pending historical rows are outside rolling rate windows but remain active. + # Completed inactive threads are covered by test_retirement. def fill(first, last): store.db.executemany('''INSERT INTO messages (id,source,recipient,text,root_id,hops,status,provenance,created) VALUES(?,'ada','grokbot','retained history',?,1,?,'manual',1)''', ((f'history-{i:06d}', f'history-{i:06d}', - 'queued' if i % 2 else 'acknowledged') for i in range(first, last))) + 'queued') for i in range(first, last))) store.db.commit() fill(0, 10000) diff --git a/tests/test_retirement.py b/tests/test_retirement.py new file mode 100644 index 0000000..35fb881 --- /dev/null +++ b/tests/test_retirement.py @@ -0,0 +1,156 @@ +import sqlite3 +import tempfile +from pathlib import Path +import unittest +from unittest.mock import patch + +from babel.core import BridgeError, Store, THREAD_IDLE_SECONDS + + +NOW = 2000000000 +OLD = NOW - THREAD_IDLE_SECONDS - 1 + + +class RetirementTests(unittest.TestCase): + def setUp(self): + self.store = Store(':memory:') + + def tearDown(self): + self.store.close() + + def message(self, mid, status='acknowledged', at=OLD, parent=None): + data = dict(source='ada', recipient='grokbot', text='retirement test', message_id=mid) + if parent: + data.update(source=parent['recipient'], recipient=parent['source'], reply_to=parent['id']) + with patch('babel.core.time.time', return_value=at): + row = self.store.stage(**data)['message'] + if status != 'draft': + self.store.approve(row['id']) + if status == 'acknowledged': + self.store.acknowledge(row['id'], row['recipient']) + if status == 'canceled': + self.store.cancel(row['id']) + return self.store._row(mid) + + def sweep(self, dry_run=False): + with patch('babel.core.time.time', return_value=NOW): + return self.store.retire_threads(dry_run=dry_run) + + def test_whole_thread_boundary_and_history_preserved(self): + first = self.message('finished-root-001') + child = self.message('finished-child-001', parent=first) + self.message('boundary-root-001', at=NOW - THREAD_IDLE_SECONDS) + active = self.message('recent-child-root') + self.message('recent-child-001', parent=active, at=NOW - 1) + before = self.store.db.execute('SELECT COUNT(*) FROM events').fetchone()[0] + preview = self.sweep(dry_run=True) + self.assertEqual(preview['eligible_threads'], 2) + self.assertEqual(preview['eligible_messages'], 3) + self.assertEqual(preview['retired_messages'], 0) + result = self.sweep() + self.assertEqual((result['active_messages'], result['retired_messages']), (2, 3)) + self.assertEqual(self.store._row(child['id'])['retired_at'], NOW) + self.assertEqual(len(self.store.history()), 5) + self.assertEqual(self.store.db.execute('SELECT COUNT(*) FROM events').fetchone()[0], before) + self.assertEqual(self.sweep()['eligible_messages'], 0) + + def test_pending_messages_and_recent_receipts_or_cancels_protect_thread(self): + for status in ('draft', 'queued'): + first = self.message('pending-root-' + status) + self.message('pending-child-' + status, status=status, parent=first) + recent = self.message('recent-receipt-01', status='queued') + canceled = self.message('recent-canceled01', status='draft') + with patch('babel.core.time.time', return_value=NOW): + self.store.acknowledge(recent['id'], recent['recipient']) + self.store.cancel(canceled['id']) + self.assertEqual(self.sweep()['eligible_messages'], 0) + + def test_polls_and_non_activity_events_do_not_extend_lifetime(self): + row = self.message('quiet-history-001') + with patch('babel.core.time.time', return_value=NOW): + self.store.history(role='ada') + self.store.message_status(row['id'], 'ada') + self.store.claim_message(row['id'], 'grokbot', 'polling-claim-001') + self.store.db.execute("INSERT INTO events(message_id,action,actor,created) VALUES(?,'manual-export-prepared','local-operator',?)", (row['id'], NOW)) + self.store.db.commit() + self.assertEqual(self.sweep()['eligible_messages'], 1) + + def test_archived_retry_receipt_and_new_reply_behavior(self): + row = self.message('retry-history-001', status='queued') + with patch('babel.core.time.time', return_value=OLD): + self.store.claim_message(row['id'], 'grokbot', 'original-claim-001') + self.store.acknowledge_claim(row['id'], 'grokbot', 'original-claim-001') + self.sweep() + retry = self.store.stage('ada', 'grokbot', 'retirement test', message_id=row['id']) + self.assertTrue(retry['duplicate']) + self.assertEqual(retry['message']['retired_at'], NOW) + self.assertEqual(self.store.acknowledge_claim(row['id'], 'grokbot', 'original-claim-001')['status'], 'acknowledged') + with self.assertRaises(BridgeError) as changed: + self.store.stage('ada', 'grokbot', 'changed text', message_id=row['id']) + self.assertEqual(changed.exception.status, 409) + with self.assertRaises(BridgeError) as retired: + self.store.stage('grokbot', 'ada', 'new reply', reply_to=row['id']) + self.assertEqual(retired.exception.status, 410) + self.assertFalse(self.store.stage('grokbot', 'ada', 'new thread')['duplicate']) + self.assertEqual(self.store.inbox('grokbot'), []) + + def test_admission_reclaims_finished_threads_when_sweep_was_missed(self): + self.message('capacity-finished') + self.message('capacity-pending1', status='queued') + with patch('babel.core.MAX_RETAINED_MESSAGES', 2), patch('babel.core.time.time', return_value=NOW): + self.store.stage('ada', 'grokbot', 'accepted', message_id='capacity-accepted') + with self.assertRaises(BridgeError) as full: + self.store.stage('ada', 'grokbot', 'blocked', message_id='capacity-blocked0') + self.assertEqual(full.exception.status, 507) + self.assertEqual(self.store.retirement_usage(), {'active_messages': 2, 'retired_messages': 1, 'total_messages': 3}) + + def test_sweep_and_reply_serialize_on_two_connections(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / 'bridge.sqlite3' + first, second = Store(path), Store(path) + try: + with patch('babel.core.time.time', return_value=OLD): + row = first.stage('ada', 'grokbot', 'old', message_id='race-thread-0001')['message'] + first.approve(row['id']); first.acknowledge(row['id'], 'grokbot') + with patch('babel.core.time.time', return_value=NOW): + # A reply committed before a sweep protects its whole thread. + second.stage('grokbot', 'ada', 'new', message_id='race-reply-00001', reply_to=row['id']) + self.assertEqual(first.retire_threads()['eligible_messages'], 0) + second.cancel('race-reply-00001') + with patch('babel.core.time.time', return_value=NOW + THREAD_IDLE_SECONDS + 1): + self.assertEqual(first.retire_threads()['eligible_messages'], 2) + with self.assertRaises(BridgeError) as closed: + second.stage('grokbot', 'ada', 'late', reply_to=row['id']) + self.assertEqual(closed.exception.status, 410) + self.assertEqual(second.db.execute('PRAGMA integrity_check').fetchone()[0], 'ok') + finally: + first.close(); second.close() + + def test_failed_sweep_rolls_back_and_restart_backup_keep_retirement(self): + self.message('rollback-root-001') + self.message('rollback-root-002') + self.store.db.execute("CREATE TRIGGER reject_retirement BEFORE UPDATE OF retired_at ON messages WHEN NEW.id='rollback-root-002' BEGIN SELECT RAISE(ABORT,'synthetic failure'); END") + self.store.db.commit() + with self.assertRaises(sqlite3.IntegrityError): + self.sweep() + self.assertEqual(self.store.retirement_usage()['retired_messages'], 0) + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / 'bridge.sqlite3' + self.store.db.execute('DROP TRIGGER reject_retirement'); self.store.db.commit() + with sqlite3.connect(path) as dest: + self.store.db.backup(dest) + persistent = Store(path) + with patch('babel.core.time.time', return_value=NOW): + persistent.retire_threads() + backup = persistent.backup(); persistent.close() + for dbpath in (path, path.parent / 'backups' / backup): + restored = Store(dbpath) + try: + self.assertEqual(restored.retirement_usage()['retired_messages'], 2) + self.assertEqual(restored.db.execute('PRAGMA user_version').fetchone()[0], 4) + finally: + restored.close() + + +if __name__ == '__main__': + unittest.main() From db7b865def6e46517f7a87404963c121531a33d6 Mon Sep 17 00:00:00 2001 From: mikkel Date: Wed, 4 Nov 2026 22:38:08 +0000 Subject: [PATCH 2/2] Exercise retirement CLI and avoid shadowed json imports --- babel/__main__.py | 2 +- tests/test_retirement.py | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/babel/__main__.py b/babel/__main__.py index 12c6fee..d4a2291 100644 --- a/babel/__main__.py +++ b/babel/__main__.py @@ -1,5 +1,4 @@ import argparse -import json import os from .core import AGENTS, BridgeError, Store from .mcp import stdio @@ -65,6 +64,7 @@ def main(): finally: store.close() elif args.mode == "retire": + import json store = Store() try: print(json.dumps(store.retire_threads(dry_run=args.dry_run)), flush=True) diff --git a/tests/test_retirement.py b/tests/test_retirement.py index 35fb881..e424bed 100644 --- a/tests/test_retirement.py +++ b/tests/test_retirement.py @@ -1,10 +1,14 @@ +import json +import os import sqlite3 +import subprocess +import sys import tempfile from pathlib import Path import unittest from unittest.mock import patch -from babel.core import BridgeError, Store, THREAD_IDLE_SECONDS +from babel.core import BridgeError, ROOT, Store, THREAD_IDLE_SECONDS NOW = 2000000000 @@ -151,6 +155,22 @@ def test_failed_sweep_rolls_back_and_restart_backup_keep_retirement(self): finally: restored.close() + def test_cli_preview_apply_and_repeat(self): + with tempfile.TemporaryDirectory() as tmp: + store = Store(Path(tmp) / 'bridge.sqlite3') + with patch('babel.core.time.time', return_value=1): + store.stage('ada', 'grokbot', 'historical', message_id='cli-history-0001') + store.approve('cli-history-0001') + store.acknowledge('cli-history-0001', 'grokbot') + store.close() + for options, retired, eligible in ((['--dry-run'], 0, 1), ([], 1, 1), (['--dry-run'], 1, 0)): + result = subprocess.run([sys.executable, '-m', 'babel', 'retire', *options], + cwd=ROOT, env={**os.environ, 'BABEL_DATA_DIR': tmp}, + capture_output=True, text=True, check=True, timeout=15) + data = json.loads(result.stdout) + self.assertEqual(data['retired_messages'], retired) + self.assertEqual(data['eligible_messages'], eligible) + if __name__ == '__main__': unittest.main()