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/object_daemon.py
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, 7 minutes ago History
object_daemon.py · 102.8 KB · 2465 lines
1#!/usr/bin/env python3
2"""
3Object Primitive Daemon — Scheduler, Queue, Events
4
5Background worker that polls trigger objects and executes target objects.
6
7Runs alongside the HTTP server, sharing file-based state (TSV).
8Does not require HTTP or auth — executes objects directly via ObjectRuntime.
9
10Usage:
11 python object_daemon.py
12 python object_daemon.py --interval 5 # poll every 5 seconds
13"""
14from __future__ import annotations
15
16import json
17import os
18import signal
19import time
20import urllib.error
21import urllib.request
22from datetime import datetime, timedelta, timezone
23from pathlib import Path
24from typing import TYPE_CHECKING, Any
25
26if TYPE_CHECKING:
27 from dbbasic_object_core.runtime.object_runtime import ObjectRuntime
28
29try:
30 from croniter import croniter
31except ImportError:
32 croniter = None
33
34import object_analytics
35import object_backup_index
36import object_backup_schedule
37import object_books_status
38import object_change_dispatch
39import object_collections
40import object_connectors
41import object_daemon_status
42import object_email
43import object_events
44import object_identity
45import object_logs
46import object_ids
47import object_materialize
48import object_notify
49import object_packages
50import object_record_changes
51import object_records
52import object_rollups
53import object_schedule
54from object_execution import ObjectExecutionFailure, ObjectExecutionRequest, execute_object
55from object_namespace import find_trigger_file, get_object_roots, resolve_object_id
56
57# Daemon state
58_running = True
59EVENT_KEEP_COUNT_ENV = "DBBASIC_EVENT_KEEP_COUNT"
60EVENT_KEEP_SECONDS_ENV = "DBBASIC_EVENT_KEEP_SECONDS"
61EVENT_CLEANUP_INTERVAL_SECONDS = 60.0
62
63# Compaction pass (docs/append-only-storage-design.md Compaction: "run on
64# a schedule or when the superseded-row ratio passes a threshold -- never
65# inline in a request"). See process_compactions.
66COMPACTION_INTERVAL_SECONDS_ENV = "DBBASIC_COMPACTION_INTERVAL_SECONDS"
67COMPACTION_BLOAT_RATIO_ENV = "DBBASIC_COMPACTION_BLOAT_RATIO"
68_DEFAULT_COMPACTION_INTERVAL_SECONDS = 3600
69_DEFAULT_COMPACTION_BLOAT_RATIO = 1.0
70COMPACTION_MARKER_NAME = ".compaction_last_run"
71
72# Stale-state auto-transition pass. The predecessor system's "48-hour
73# auto-approve" job (waiting_on_client -> approved on tasks) was written
74# but never scheduled anywhere, silently stranding 200+ records in a
75# waiting state forever. To make that class of mistake impossible here,
76# this pass ships ON by default -- see _DEFAULT_AUTO_TRANSITION_RULES --
77# and requires no setup beyond running the daemon. See
78# process_stale_transitions.
79AUTO_TRANSITION_RULES_ENV = "DBBASIC_AUTO_TRANSITION_RULES"
80AUTO_TRANSITION_INTERVAL_SECONDS_ENV = "DBBASIC_AUTO_TRANSITION_INTERVAL_SECONDS"
81_DEFAULT_AUTO_TRANSITION_INTERVAL_SECONDS = 3600
82AUTO_TRANSITION_MARKER_NAME = ".auto_transition_last_run"
83AUTO_TRANSITION_ACTOR = "daemon:auto-transition"
84_DEFAULT_AUTO_TRANSITION_RULES = json.dumps([
85 {"collection": "tasks", "field": "status", "from": "waiting_on_client",
86 "to": "approved", "after_hours": 48},
87])
88
89# Collections named in a rule but not found on disk (the owning package
90# isn't installed) are logged once per process, not once per poll --
91# see _apply_auto_transition_rule.
92_WARNED_UNKNOWN_AUTO_TRANSITION_COLLECTIONS: set[str] = set()
93
94# Materialize pass (plan/vocabulary/61-materialize-spec.md, object_materialize.py).
95# Unlike process_rollups (whose due-gate lives entirely on each
96# rollup_definitions row -- see process_rollups' own docstring),
97# materialize's Events section explicitly asks for process_stale_
98# transitions' marker-file-gated shape instead: "riding the exact
99# marker-file-gated, try/except-per-item pattern process_stale_
100# transitions already establishes." See process_materializations.
101MATERIALIZE_INTERVAL_SECONDS_ENV = "DBBASIC_MATERIALIZE_INTERVAL_SECONDS"
102_DEFAULT_MATERIALIZE_INTERVAL_SECONDS = 3600
103MATERIALIZE_MARKER_NAME = ".materialize_last_run"
104# 12 notify: the cursor file holds the ISO timestamp of the last record-change
105# entry process_notifications has already turned into notifications. Unlike the
106# other passes' interval markers, this is a POSITION (content), not a clock
107# (mtime) -- the pass runs every poll for near-instant delivery and advances
108# the cursor past what it processed. First run stamps it at "now" so a fresh
109# install never backfills notifications for the entire change history.
110NOTIFY_CURSOR_NAME = ".notify_cursor"
111
112# Definitions referencing a source/output/child collection that doesn't
113# exist yet (the owning package isn't installed) are logged once per
114# process, not once per poll -- mirrors _WARNED_UNKNOWN_AUTO_TRANSITION_
115# COLLECTIONS exactly (61's Degradation section names this precedent).
116_WARNED_UNKNOWN_MATERIALIZE_COLLECTIONS: set[str] = set()
117
118
119def log(msg, level='INFO'):
120 ts = time.strftime('%Y-%m-%d %H:%M:%S')
121 print(f"[{ts}] [{level}] {msg}")
122
123
124_last_beat = 0.0
125
126
127def _beat(base_dir, *, now=None):
128 """Touch the data dir's daemon heartbeat (object_daemon_status.
129 DAEMON_HEARTBEAT_NAME), at most once per DAEMON_HEARTBEAT_EVERY seconds.
130 It is what lets /daemon/status and the server's startup line say "no
131 daemon is running" instead of a box with scheduled passes simply looking
132 quiet. One small file, overwritten in place: bounded by construction."""
133 global _last_beat
134 current = time.time() if now is None else now
135 if current - _last_beat < object_daemon_status.DAEMON_HEARTBEAT_EVERY:
136 return
137 _last_beat = current
138 try:
139 path = Path(base_dir) / object_daemon_status.DAEMON_HEARTBEAT_NAME
140 path.parent.mkdir(parents=True, exist_ok=True)
141 path.write_text(json.dumps({"pid": os.getpid(), "at": int(current)}) + "\n")
142 except OSError as exc:
143 log(f"Heartbeat not written: {exc}", 'WARN')
144
145
146# Task ids already reported as unschedulable in this process, so the ERROR
147# line appears once per task per daemon start rather than once per poll.
148_REPORTED_UNSCHEDULABLE: set[str] = set()
149
150
151def _unschedulable_reason(task) -> str | None:
152 """Why a task can never get a next run, or None when it can.
153
154 A cron task with croniter missing, or with an expression croniter
155 rejects, used to be skipped with no trace at all (the only hint was one
156 boot line about croniter), so a stock install ran none of its 15
157 package schedules and nothing anywhere said so."""
158 task_type = task.get('type', '')
159 if task_type == 'cron':
160 if not croniter:
161 return ("croniter is not installed, so this cron schedule can never "
162 "run; install the 'scheduler' extra: pip install -e '.[scheduler]'")
163 return f"cron expression {task.get('schedule', '')!r} is not valid"
164 if task_type == 'onetime':
165 return f"onetime schedule {task.get('schedule', '')!r} is not an ISO timestamp"
166 if task_type == 'interval':
167 return f"interval schedule {task.get('schedule', '')!r} is not a positive number of seconds"
168 return f"unknown schedule type {task_type!r} (expected cron, onetime or interval)"
169
170
171def _report_unschedulable(obj, key, task):
172 """Record on the task itself (visible in GET /daemon/scheduler/tasks and
173 counted by /daemon/status) and log once per process -- never a silent
174 skip."""
175 reason = _unschedulable_reason(task)
176 if task.get('error') != reason:
177 task['error'] = reason
178 obj.state_manager.set(key, json.dumps(task))
179 task_id = str(task.get('id') or key)
180 if task_id not in _REPORTED_UNSCHEDULABLE:
181 _REPORTED_UNSCHEDULABLE.add(task_id)
182 log(f"Scheduler: task {task_id} ({task.get('object_id')}) cannot be "
183 f"scheduled: {reason}", 'ERROR')
184
185
186def _object_roots() -> list[Path]:
187 """Return object source roots in lookup order."""
188 return get_object_roots()
189
190
191def _find_trigger_file(trigger_name: str) -> Path | None:
192 """Find a trigger object in the configured object roots."""
193 return find_trigger_file(trigger_name)
194
195
196# --- Scheduler ---
197
198def process_scheduler(runtime: ObjectRuntime):
199 """Check scheduler for due tasks and execute them."""
200 scheduler_file = _find_trigger_file('scheduler')
201 if scheduler_file is None:
202 return
203
204 obj = runtime.load_object(scheduler_file) # ID = 'scheduler' (filename stem)
205 obj.state_manager.reload() # Re-read from disk (server may have written new tasks)
206 state = obj.state_manager.get_all()
207 now = int(time.time())
208
209 for key, value in list(state.items()):
210 if not key.startswith('task_'):
211 continue
212
213 try:
214 task = json.loads(value)
215 except (json.JSONDecodeError, TypeError):
216 continue
217
218 if task.get('status') != 'active':
219 continue
220
221 # Calculate next_run if not set
222 next_run = task.get('next_run')
223 if next_run is None:
224 next_run = _calculate_next_run(task)
225 if next_run is None:
226 _report_unschedulable(obj, key, task)
227 continue
228 task['next_run'] = next_run
229 task.pop('error', None)
230 obj.state_manager.set(key, json.dumps(task))
231
232 if next_run > now:
233 continue
234
235 # Task is due — execute target
236 target_id = task.get('object_id')
237 method = task.get('method', 'POST')
238 payload = task.get('payload', {})
239
240 if not target_id:
241 continue
242
243 if task.get('kind') == object_schedule.TASK_KIND:
244 _run_scheduled_method(runtime, obj, key, task, now)
245 continue
246
247 log(f"Scheduler: executing {target_id}.{method} (task {task['id']})")
248
249 run_started = time.time()
250 run_result = None
251 run_error: Exception | None = None
252 try:
253 run_result = _execute_target(runtime, target_id, method, payload)
254 log(f"Scheduler: {target_id}.{method} completed")
255 except Exception as e:
256 run_error = e
257 log(f"Scheduler: {target_id}.{method} failed: {e}", 'ERROR')
258 _log_task_failure(target_id, method, task.get('id'), e)
259 _record_scheduler_run(
260 task, target_id, method,
261 started=run_started,
262 duration_ms=int((time.time() - run_started) * 1000),
263 result=run_result,
264 error=run_error,
265 )
266
267 # Update task
268 task['last_run'] = now
269 task['run_count'] = task.get('run_count', 0) + 1
270 _stamp_outcome(task, now, run_error)
271
272 if task.get('type') == 'onetime':
273 task['status'] = 'completed'
274 task['next_run'] = None
275 else:
276 task['next_run'] = _calculate_next_run(task, after=now)
277
278 obj.state_manager.set(key, json.dumps(task))
279
280
281# Self-scheduled tasks (object_schedule) whose object or method is gone,
282# already logged in this process: one WARN per task per daemon start, not
283# one per interval.
284_REPORTED_GONE: set[str] = set()
285
286
287LAST_ERROR_MAX = 500
288
289
290def _stamp_outcome(row, now, failure):
291 """Record a run's outcome on the task row itself.
292
293 A scheduled method that raised, timed out or was killed used to be
294 indistinguishable from a healthy one: run_count went up, nothing else
295 changed. Now the row says so -- last_error, last_error_at and
296 consecutive_failures (reset by the next success; last_error is kept so
297 "it failed once on Tuesday" is still readable).
298 """
299 if failure:
300 row['last_error'] = str(failure)[:LAST_ERROR_MAX]
301 row['last_error_at'] = now
302 row['consecutive_failures'] = int(row.get('consecutive_failures') or 0) + 1
303 elif row.get('consecutive_failures'):
304 row['consecutive_failures'] = 0
305
306
307def _log_task_failure(target_id, method, task_id, failure, base_dir=None):
308 """One line in the TARGET object's own log, where its owner looks."""
309 try:
310 object_logs.append_object_log(
311 str(target_id), 'ERROR',
312 f"Scheduled {method} failed (task {task_id}): {failure}",
313 base_dir or os.environ.get('DBBASIC_DATA_DIR', 'data'),
314 scheduled_task=str(task_id), scheduled_method=str(method),
315 )
316 except Exception: # noqa: BLE001 - a log line must never break the pass
317 pass
318
319
320def _run_scheduled_method(runtime, obj, key, task, now):
321 """Run one method an object scheduled for itself (``_schedule``).
322
323 It goes through execute_object like every other target, so a user
324 object runs in its sandbox and a system object as usual. The payload
325 carries no identity: the method runs as itself, never as whoever
326 scheduled it and never as the admin. An object or method that has gone
327 is skipped and logged, and the row keeps its interval (a reinstall
328 brings it back); destroying the object through the API removes it.
329 """
330 target_id = str(task.get('object_id'))
331 method = str(task.get('method') or '')
332 task_id = str(task.get('id') or key)
333 error_text = None
334 run_result = None
335 run_error: Exception | None = None
336 run_started = time.time()
337
338 if _find_object_file(target_id) is None:
339 error_text = f"object {target_id} no longer exists; skipped"
340 else:
341 log(f"Scheduler: executing {target_id}.{method} (task {task_id})")
342 request = ObjectExecutionRequest(
343 object_id=target_id, method=method, payload={}, named_method=True)
344 result = execute_object(runtime, request)
345 if result.ok:
346 run_result = result.result
347 log(f"Scheduler: {target_id}.{method} completed")
348 _REPORTED_GONE.discard(task_id)
349 elif result.error is not None and result.error.type in (
350 'MethodNotSupportedError', 'ObjectNotFoundError'):
351 error_text = f"{target_id} has no method {method!r} any more; skipped"
352 else:
353 run_error = ObjectExecutionFailure(result)
354 log(f"Scheduler: {target_id}.{method} failed: {run_error}", 'ERROR')
355 _log_task_failure(target_id, method, task_id, run_error)
356
357 if error_text is not None:
358 if task_id not in _REPORTED_GONE:
359 _REPORTED_GONE.add(task_id)
360 log(f"Scheduler: task {task_id}: {error_text}", 'WARN')
361 _log_task_failure(target_id, method, task_id, error_text)
362 else:
363 _record_scheduler_run(
364 task, target_id, method,
365 started=run_started,
366 duration_ms=int((time.time() - run_started) * 1000),
367 result=run_result,
368 error=run_error,
369 )
370
371 def write_back(state):
372 # Re-read under the lock: the method may have unscheduled itself
373 # (the row must stay gone) or changed its interval (keep the new one).
374 current = state.get(key)
375 try:
376 row = json.loads(current) if isinstance(current, str) else None
377 except ValueError:
378 row = None
379 if not isinstance(row, dict):
380 return
381 if error_text is None:
382 row['last_run'] = now
383 row['run_count'] = row.get('run_count', 0) + 1
384 row.pop('error', None)
385 _stamp_outcome(row, now, run_error)
386 else:
387 row['error'] = error_text
388 _stamp_outcome(row, now, error_text)
389 if row.get('next_run') == task.get('next_run'): # not rescheduled meanwhile
390 row['next_run'] = _calculate_next_run(row, after=now)
391 state[key] = json.dumps(row)
392
393 modify = getattr(obj.state_manager, 'modify', None)
394 if callable(modify):
395 modify(write_back)
396 else: # a legacy runtime's manager: best effort, as before
397 state = {key: json.dumps(task)}
398 write_back(state)
399 obj.state_manager.set(key, state[key])
400
401
402def _record_scheduler_run(task, target_id, method, *, started, duration_ms,
403 result, error):
404 """Append one scheduler_runs row -- run history an operator can query.
405
406 A run's outcome must be a RECORD, not a stdout line only ssh can reach
407 (the observability hole that let q9's auto-approve and this server's own
408 scheduler passes sit dead unnoticed). Best-effort: skips silently when
409 the scheduler_runs collection is not installed (system-dashboard ships
410 it) and never breaks the pass.
411 """
412 try:
413 base_dir = os.environ.get("DBBASIC_DATA_DIR", "data")
414 row = {
415 "id": object_ids.new_uuid4(),
416 "task_id": str(task.get("id") or ""),
417 "object_id": str(target_id),
418 "method": str(method),
419 "ok": "false" if error is not None else "true",
420 "started_at": datetime.fromtimestamp(started, tz=timezone.utc).isoformat(),
421 "duration_ms": str(int(duration_ms)),
422 "result": "" if error is not None or result is None else json.dumps(result)[:2000],
423 "error": str(error)[:2000] if error is not None else "",
424 "error_type": type(error).__name__ if error is not None else "",
425 }
426 object_records.create_collection_record(
427 "scheduler_runs", row, base_dir=base_dir, actor="daemon:scheduler"
428 )
429 except Exception:
430 pass # observability must never break the scheduling pass
431
432
433def _calculate_next_run(task, after=None):
434 """Calculate next run time for a task."""
435 schedule = task.get('schedule', '')
436 task_type = task.get('type', '')
437
438 if after is None:
439 after = int(time.time())
440
441 if task_type == 'cron' and croniter:
442 try:
443 cron = croniter(schedule, after)
444 return int(cron.get_next(float))
445 except (ValueError, KeyError):
446 return None
447
448 elif task_type == 'onetime':
449 try:
450 dt = datetime.fromisoformat(schedule.replace('Z', '+00:00'))
451 return int(dt.timestamp())
452 except (ValueError, TypeError):
453 return None
454
455 elif task_type == 'interval':
456 # object_schedule (_schedule): every N seconds, counted from the
457 # last run -- a daemon that was down does not owe a backlog.
458 try:
459 seconds = int(str(schedule).strip())
460 except (ValueError, TypeError):
461 return None
462 return after + seconds if seconds > 0 else None
463
464 return None
465
466
467# --- Queue ---
468
469def process_queue(runtime: ObjectRuntime, max_messages=10):
470 """Dequeue messages and execute target objects."""
471 queue_file = _find_trigger_file('queue')
472 if queue_file is None:
473 return
474
475 obj = runtime.load_object(queue_file) # ID = 'queue' (filename stem)
476 obj.state_manager.reload() # Re-read from disk
477 state = obj.state_manager.get_all()
478 now = int(time.time())
479
480 # Find pending, visible messages
481 messages = []
482 for key, value in state.items():
483 if not key.startswith('msg_'):
484 continue
485
486 try:
487 msg = json.loads(value)
488 except (json.JSONDecodeError, TypeError):
489 continue
490
491 if msg.get('status') != 'pending':
492 continue
493
494 # Check expiration. `or`-style defaulting rather than .get(key,
495 # default): object_daemon_control.enqueue_message always WRITES
496 # expires_at, using None to mean "never expires", so the key exists
497 # and .get's default never applied -- every message enqueued through
498 # the official API raised TypeError here and took the whole pass
499 # down with it. The queue was fully built and unusable for exactly
500 # that reason.
501 expires_at = msg.get('expires_at')
502 if expires_at is not None and expires_at < now:
503 msg['status'] = 'expired'
504 obj.state_manager.set(key, json.dumps(msg))
505 continue
506
507 # Check visibility (same defaulting hazard: visible_after is always
508 # written, and a null there means "runnable now").
509 visible_after = msg.get('visible_after')
510 if visible_after is not None and visible_after > now:
511 continue
512
513 messages.append((key, msg))
514
515 # Sort by priority (highest first), then timestamp (oldest first)
516 messages.sort(key=lambda m: (-m[1].get('priority_level', 2), m[1].get('created_at', 0)))
517
518 # Process up to max_messages
519 for key, msg in messages[:max_messages]:
520 body = msg.get('message', {})
521 if not isinstance(body, dict):
522 continue
523
524 target_id = body.get('object_id')
525 if not target_id:
526 continue
527
528 method = body.get('method', 'POST')
529 payload = body.get('payload', {})
530
531 log(f"Queue: executing {target_id}.{method} (msg {msg['id']}, queue {msg.get('queue_name')})")
532
533 # Mark as processing
534 msg['status'] = 'processing'
535 msg['dequeued_at'] = now
536 obj.state_manager.set(key, json.dumps(msg))
537
538 try:
539 _execute_target(runtime, target_id, method, payload)
540 msg['status'] = 'completed'
541 msg['completed_at'] = int(time.time())
542 log(f"Queue: {target_id}.{method} completed")
543 except Exception as e:
544 log(f"Queue: {target_id}.{method} failed: {e}", 'ERROR')
545 msg['attempts'] = msg.get('attempts', 0) + 1
546 if msg['attempts'] >= msg.get('max_attempts', 3):
547 msg['status'] = 'failed'
548 msg['failed_at'] = int(time.time())
549 else:
550 msg['status'] = 'pending'
551 msg['visible_after'] = int(time.time()) + (2 ** msg['attempts'])
552
553 obj.state_manager.set(key, json.dumps(msg))
554
555
556# --- Events ---
557
558def process_events(runtime: ObjectRuntime):
559 """Deliver events to subscribers via callback URLs."""
560 events_file = _find_trigger_file('events')
561 if events_file is None:
562 return
563
564 obj = runtime.load_object(events_file) # ID = 'events' (filename stem)
565 obj.state_manager.reload() # Re-read from disk
566 state = obj.state_manager.get_all()
567
568 # Collect subscriptions and events
569 subscriptions = {}
570 events = {}
571
572 for key, value in state.items():
573 try:
574 data = json.loads(value)
575 except (json.JSONDecodeError, TypeError):
576 continue
577
578 if key.startswith('sub_'):
579 callback = data.get('callback_url')
580 if callback:
581 subscriptions[key] = data
582 elif key.startswith('event_'):
583 events[key] = data
584
585 if not subscriptions or not events:
586 return
587
588 # Sort events by timestamp
589 sorted_events = sorted(events.values(), key=lambda e: e.get('timestamp', 0))
590
591 for sub_key, sub in subscriptions.items():
592 event_type = sub.get('event_type')
593 last_event_id = sub.get('last_event_id')
594 callback_url = sub.get('callback_url')
595
596 # Find events for this subscription
597 matching = [e for e in sorted_events if e.get('event_type') == event_type]
598
599 # Skip events already delivered
600 if last_event_id:
601 found = False
602 pending = []
603 for e in matching:
604 if found:
605 pending.append(e)
606 elif e.get('id') == last_event_id:
607 found = True
608 if not found:
609 # last_event_id not found, deliver all
610 pending = matching
611 else:
612 pending = matching
613
614 if not pending:
615 continue
616
617 # Deliver events
618 for event in pending:
619 status_code = None
620 try:
621 req = urllib.request.Request(
622 callback_url,
623 data=json.dumps(event).encode('utf-8'),
624 headers={'Content-Type': 'application/json'},
625 method='POST',
626 )
627 with urllib.request.urlopen(req, timeout=5) as resp:
628 if hasattr(resp, 'getcode'):
629 status_code = resp.getcode()
630 else:
631 status_code = getattr(resp, 'status', None)
632 log(f"Events: delivered {event['event_type']} ({event['id']}) to {sub['id']}")
633 sub = object_events.record_subscription_delivery(
634 sub,
635 event,
636 success=True,
637 status_code=status_code,
638 )
639 obj.state_manager.set(sub_key, json.dumps(sub))
640 except (urllib.error.URLError, OSError) as e:
641 status_code = getattr(e, 'code', None)
642 log(f"Events: failed to deliver to {callback_url}: {e}", 'WARN')
643 sub = object_events.record_subscription_delivery(
644 sub,
645 event,
646 success=False,
647 status_code=status_code,
648 error=str(e),
649 )
650 obj.state_manager.set(sub_key, json.dumps(sub))
651 break
652
653
654# --- Rate Limit Cleanup ---
655
656def cleanup_ratelimit(max_age=120, *, base_dir: Path | str = "data"):
657 """Delete rate limit files older than max_age seconds."""
658 ratelimit_dir = Path(base_dir) / 'ratelimit'
659 if not ratelimit_dir.exists():
660 return
661
662 now = time.time()
663 cutoff = now - max_age
664 cleaned = 0
665
666 for f in ratelimit_dir.iterdir():
667 if not f.is_file() or not f.name.endswith('.txt'):
668 continue
669 try:
670 # Check if file has any recent timestamps
671 has_recent = False
672 for line in f.read_text().strip().split('\n'):
673 if line:
674 ts = float(line)
675 if ts > cutoff:
676 has_recent = True
677 break
678 if not has_recent:
679 f.unlink()
680 cleaned += 1
681 except (ValueError, IOError, OSError):
682 # Corrupt or unreadable — safe to remove
683 try:
684 f.unlink()
685 cleaned += 1
686 except OSError:
687 pass
688
689 if cleaned:
690 log(f"Cleanup: removed {cleaned} expired rate limit file(s)")
691
692
693def cleanup_events(
694 *,
695 base_dir: Path | str = "data",
696 keep_count: int | None = None,
697 keep_seconds: int | None = None,
698):
699 """Prune old event queue rows while preserving subscriptions."""
700 if keep_count is None:
701 keep_count = _env_int(EVENT_KEEP_COUNT_ENV, object_events.DEFAULT_EVENT_KEEP_COUNT)
702 if keep_seconds is None:
703 keep_seconds = _env_int(EVENT_KEEP_SECONDS_ENV, object_events.DEFAULT_EVENT_KEEP_SECONDS)
704
705 result = object_events.prune_events(
706 base_dir=base_dir,
707 keep_count=keep_count,
708 keep_seconds=keep_seconds,
709 )
710 if result["deleted"]:
711 log(f"Cleanup: removed {result['deleted']} expired event row(s)")
712 return result
713
714
715def _env_int(name: str, default: int) -> int:
716 value = os.environ.get(name, "").strip()
717 if not value:
718 return default
719 try:
720 return int(value)
721 except ValueError:
722 return default
723
724
725def _env_float(name: str, default: float) -> float:
726 value = os.environ.get(name, "").strip()
727 if not value:
728 return default
729 try:
730 return float(value)
731 except ValueError:
732 return default
733
734
735# --- Compaction ---
736
737def process_compactions(*, base_dir: Path | str = "data") -> dict | None:
738 """Compact over-threshold append-mode collections on a timer.
739
740 Runs at most once per DBBASIC_COMPACTION_INTERVAL_SECONDS (default
741 3600 -- an hour), gated by a marker FILE (`.compaction_last_run` under
742 `base_dir`) rather than an in-process variable like the event-cleanup
743 pass above uses: a file marker survives a daemon restart, and if more
744 than one daemon process ever points at the same data dir, whichever
745 one's write lands last simply wins that interval's marker -- there is
746 no harm in an occasional double-run of a compaction that is itself
747 idempotent-per-collection (compact_collection on an already-compacted
748 file is a correctly-reported no-op).
749
750 Every collection whose schema currently declares "storage": "append"
751 (object_records.list_append_collection_stats) is compacted when BOTH:
752 - its physical row count is at or above DBBASIC_APPEND_COMPACT_
753 MIN_ROWS (object_records.append_compact_min_rows -- the same
754 floor object_records._maybe_flag_auto_compact uses for its own
755 inline auto-compact trigger on ordinary writes), AND
756 - its bloat_ratio is at or above DBBASIC_COMPACTION_BLOAT_RATIO
757 (default 1.0 -- dead rows at least matching live rows).
758 A stats entry this call can't get real numbers for (list_append_
759 collection_stats defaults to allow_fold=True, so this is not expected
760 in practice, but a None/estimated physical_rows or bloat_ratio is
761 skipped rather than guessed at) is left alone; it will be reconsidered
762 on the next interval.
763
764 Each collection's compaction is wrapped in its own try/except: one
765 collection failing (a lock contention, a mid-flight schema change, a
766 permissions error) is logged and skipped, never allowed to stop the
767 rest of the pass or propagate out of this function -- the daemon is
768 an optional process (nothing else may depend on it running), and a
769 single bad collection must not take an entire poll interval's worth
770 of compaction down with it. The daemon's own main loop wraps this
771 call in a try/except too, belt and suspenders.
772
773 Returns None when the interval hasn't elapsed yet (no work attempted
774 this call). Otherwise returns {"checked": <int>, "compacted": [{
775 "collection", "rows_before", "rows_after", "bytes_before",
776 "bytes_after"}, ...]} -- mainly for tests and manual/CLI invocation;
777 the daemon's own loop only logs.
778 """
779 interval = _env_int(COMPACTION_INTERVAL_SECONDS_ENV, _DEFAULT_COMPACTION_INTERVAL_SECONDS)
780 marker_path = Path(base_dir) / COMPACTION_MARKER_NAME
781 now = time.time()
782 try:
783 last_run = marker_path.stat().st_mtime
784 except OSError:
785 last_run = 0.0
786
787 if now - last_run < interval:
788 return None
789
790 marker_path.parent.mkdir(parents=True, exist_ok=True)
791 marker_path.write_text(str(now))
792
793 bloat_threshold = _env_float(COMPACTION_BLOAT_RATIO_ENV, _DEFAULT_COMPACTION_BLOAT_RATIO)
794 min_rows = object_records.append_compact_min_rows()
795
796 try:
797 stats = object_records.list_append_collection_stats(base_dir=base_dir)
798 except Exception as e:
799 log(f"Compaction: could not list append collections: {e}", "ERROR")
800 return {"checked": 0, "compacted": []}
801
802 compacted = []
803 for entry in stats:
804 collection = entry.get("collection")
805 try:
806 physical_rows = entry.get("physical_rows")
807 bloat_ratio = entry.get("bloat_ratio")
808 if physical_rows is None or bloat_ratio is None:
809 continue
810 if physical_rows < min_rows or bloat_ratio < bloat_threshold:
811 continue
812
813 summary = object_records.compact_collection(collection, base_dir=base_dir)
814 log(
815 f"Compaction: {collection} rows {summary['rows_before']}->"
816 f"{summary['rows_after']}, bytes {summary['bytes_before']}->"
817 f"{summary['bytes_after']}"
818 )
819 compacted.append({"collection": collection, **summary})
820 except Exception as e:
821 log(f"Compaction: {collection} failed: {e}", "ERROR")
822 continue
823
824 return {"checked": len(stats), "compacted": compacted}
825
826
827# --- Stale-state auto-transition ---
828
829def auto_transition_rules_from_env() -> list[dict]:
830 """Parse DBBASIC_AUTO_TRANSITION_RULES into a list of clean rule dicts.
831
832 Unset -> _DEFAULT_AUTO_TRANSITION_RULES (tasks' waiting_on_client ->
833 approved after 48h). Set to "" or "[]" -> [] (the pass runs every
834 interval, finds nothing configured, and logs a zero-work summary
835 line rather than silently vanishing -- see process_stale_transitions).
836 A malformed entry (missing string field, unparseable after_hours) is
837 dropped with a warning rather than aborting the whole list; a
838 malformed *list* (bad JSON, not a JSON array) disables every rule and
839 is logged loudly, since silently falling back to the default here
840 would hide a real configuration mistake.
841 """
842 raw = os.environ.get(AUTO_TRANSITION_RULES_ENV)
843 if raw is None:
844 raw = _DEFAULT_AUTO_TRANSITION_RULES
845 text = raw.strip()
846 if not text:
847 return []
848
849 try:
850 parsed = json.loads(text)
851 except json.JSONDecodeError as e:
852 log(f"Auto-transition: {AUTO_TRANSITION_RULES_ENV} is not valid JSON, disabling: {e}", "ERROR")
853 return []
854 if not isinstance(parsed, list):
855 log(f"Auto-transition: {AUTO_TRANSITION_RULES_ENV} must be a JSON list, disabling", "ERROR")
856 return []
857
858 rules = []
859 for entry in parsed:
860 if not isinstance(entry, dict):
861 log(f"Auto-transition: skipping non-object rule: {entry!r}", "WARN")
862 continue
863 collection = entry.get("collection")
864 field = entry.get("field")
865 from_value = entry.get("from")
866 to_value = entry.get("to")
867 if not all(isinstance(v, str) and v for v in (collection, field, from_value, to_value)):
868 log(f"Auto-transition: skipping malformed rule (missing collection/field/from/to): {entry!r}", "WARN")
869 continue
870 try:
871 after_hours = float(entry.get("after_hours"))
872 except (TypeError, ValueError):
873 log(f"Auto-transition: skipping rule with invalid after_hours: {entry!r}", "WARN")
874 continue
875 rules.append({
876 "collection": collection,
877 "field": field,
878 "from": from_value,
879 "to": to_value,
880 "after_hours": after_hours,
881 })
882 return rules
883
884
885def _parse_iso_timestamp(value: Any) -> datetime | None:
886 if not isinstance(value, str) or not value:
887 return None
888 try:
889 parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
890 except ValueError:
891 return None
892 if parsed.tzinfo is None:
893 parsed = parsed.replace(tzinfo=timezone.utc)
894 return parsed
895
896
897def _latest_field_entry_timestamps(
898 collection: str, field: str, from_value: str, *, base_dir: Path | str
899) -> dict[str, str]:
900 """Best-effort record id -> timestamp of the most recent change that
901 set `field` to `from_value`, built from ONE sequential read of the
902 collection's record-change log (object_record_changes.CHANGES_FILE).
903
904 This is the most accurate signal available for "how long has this
905 record been sitting in this state": it answers exactly the question
906 the FSM cares about, unlike a record's own `created_at` (when the row
907 was first made, not when it entered THIS state) or a generic
908 `updated_at` (bumped by any field edit, not just this one). It only
909 stays cheap because it is read once per rule per pass -- not once per
910 candidate record -- and the log is append-ordered, so a later entry
911 for the same id simply overwrites an earlier one as this walks the
912 file forward, leaving the most recent one behind.
913
914 Returns {} when the log doesn't exist yet or can't be read; callers
915 fall back to the record's own fields in that case (see
916 _record_age_seconds).
917 """
918 try:
919 path = object_record_changes.record_changes_file(collection, base_dir=base_dir)
920 except object_collections.InvalidCollectionNameError:
921 return {}
922 if not path.exists():
923 return {}
924
925 try:
926 text = path.read_text(encoding="utf-8")
927 except OSError:
928 return {}
929
930 timestamps: dict[str, str] = {}
931 for line in text.splitlines():
932 if not line.strip():
933 continue
934 try:
935 entry = json.loads(line)
936 except json.JSONDecodeError:
937 continue
938 if not isinstance(entry, dict):
939 continue
940 after = entry.get("after")
941 if not isinstance(after, dict) or after.get(field) != from_value:
942 continue
943 record_id = entry.get("record_id")
944 timestamp = entry.get("timestamp")
945 if isinstance(record_id, str) and isinstance(timestamp, str):
946 timestamps[record_id] = timestamp
947 return timestamps
948
949
950def _record_age_seconds(
951 record: dict[str, str],
952 record_id: str,
953 change_timestamps: dict[str, str],
954 *,
955 now: datetime,
956) -> float | None:
957 """Return how long `record` has held its current value, in seconds, or
958 None when no usable timestamp exists at all (caller skips the record
959 rather than guessing).
960
961 Preference order, documented honestly: the record-change log's entry
962 for the change that set this record's field to its current value
963 (most accurate -- see _latest_field_entry_timestamps), then an
964 explicit `updated_at` field on the record itself (cheap, no schema in
965 this codebase declares one yet, but a future one might), then
966 `created_at` (tasks.json's only timestamp field today -- a real but
967 honestly-worse proxy, since it marks row creation, not state entry).
968 """
969 for source in (
970 change_timestamps.get(record_id),
971 record.get("updated_at"),
972 record.get("created_at"),
973 ):
974 parsed = _parse_iso_timestamp(source)
975 if parsed is not None:
976 return (now - parsed).total_seconds()
977 return None
978
979
980def _apply_auto_transition_rule(rule: dict, *, base_dir: Path | str) -> int:
981 """Apply one rule and return the count of records actually moved.
982
983 Every failure mode here is a skip, never an abort: an unknown
984 collection (the owning package isn't installed) is logged once and
985 skipped; a record with no usable timestamp is skipped; a record whose
986 live value has already moved on since it was listed is skipped; and a
987 write rejected by the schema (e.g. a transitions map that no longer
988 allows this move) is logged and skipped, matching process_compactions'
989 per-item isolation posture -- one bad record must never stop the rest
990 of the rule, and one bad rule must never stop the rest of the pass.
991 """
992 collection = rule["collection"]
993 field = rule["field"]
994 from_value = rule["from"]
995 to_value = rule["to"]
996 after_hours = rule["after_hours"]
997
998 try:
999 records = object_records.read_collection_records(collection, base_dir=base_dir)
1000 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError):
1001 if collection not in _WARNED_UNKNOWN_AUTO_TRANSITION_COLLECTIONS:
1002 log(
1003 f"Auto-transition: collection '{collection}' not found (package not "
1004 f"installed?), skipping rule -- will keep checking, logged once",
1005 "WARN",
1006 )
1007 _WARNED_UNKNOWN_AUTO_TRANSITION_COLLECTIONS.add(collection)
1008 return 0
1009
1010 _WARNED_UNKNOWN_AUTO_TRANSITION_COLLECTIONS.discard(collection)
1011
1012 candidates = [r for r in records if r.get(field) == from_value]
1013 if not candidates:
1014 return 0
1015
1016 change_timestamps = _latest_field_entry_timestamps(collection, field, from_value, base_dir=base_dir)
1017 cutoff_seconds = after_hours * 3600.0
1018 now = datetime.now(timezone.utc)
1019
1020 moved = 0
1021 for record in candidates:
1022 record_id = record.get("id")
1023 if not record_id:
1024 continue
1025
1026 age_seconds = _record_age_seconds(record, record_id, change_timestamps, now=now)
1027 if age_seconds is None or age_seconds < cutoff_seconds:
1028 continue
1029
1030 try:
1031 current = object_records.get_collection_record(collection, record_id, base_dir=base_dir)
1032 except object_records.RecordNotFoundError:
1033 continue # deleted since the listing above
1034 if current.get(field) != from_value:
1035 continue # moved on already -- someone/something got there first
1036
1037 try:
1038 object_records.update_collection_record(
1039 collection, record_id, {field: to_value},
1040 base_dir=base_dir, actor=AUTO_TRANSITION_ACTOR,
1041 )
1042 moved += 1
1043 except Exception as e:
1044 log(
1045 f"Auto-transition: {collection}/{record_id} {field} "
1046 f"'{from_value}'->'{to_value}' failed: {e}",
1047 "ERROR",
1048 )
1049 continue
1050
1051 return moved
1052
1053
1054def process_stale_transitions(*, base_dir: Path | str = "data") -> dict | None:
1055 """Auto-transition records that have sat in one FSM state too long.
1056
1057 Runs at most once per DBBASIC_AUTO_TRANSITION_INTERVAL_SECONDS
1058 (default 3600) gated by a marker FILE (`.auto_transition_last_run`
1059 under `base_dir`), the same pattern process_compactions above uses
1060 and for the same reason: a file marker survives a daemon restart, so
1061 the 48-hour clock this pass exists to enforce is never quietly reset
1062 by a deploy.
1063
1064 Rules come from DBBASIC_AUTO_TRANSITION_RULES (see
1065 auto_transition_rules_from_env), a compact JSON list of
1066 {"collection", "field", "from", "to", "after_hours"}. This pass ships
1067 ON by default -- the empty-env case still resolves to a real rule
1068 (tasks' waiting_on_client -> approved after 48h) -- because the
1069 predecessor system's version of this job was written but never
1070 scheduled, and 200+ records sat stranded as a result. Setting the env
1071 to "" or "[]" is how an operator opts back out.
1072
1073 Every rule is applied independently and wrapped in its own try/except
1074 (_apply_auto_transition_rule already isolates per-record failures;
1075 this is belt and suspenders against a rule failing before it gets
1076 that far, e.g. a read_collection_records call raising something other
1077 than the two "not installed" exceptions it explicitly handles) --
1078 one bad rule is logged and skipped, never allowed to stop the rest of
1079 the pass.
1080
1081 Always logs exactly one summary line per run (even a no-op run, with
1082 zero rules configured or zero records moved) so the pass's activity
1083 -- or deliberate silence -- is visible in the daemon's own log rather
1084 than something that has to be inferred. Returns None when the
1085 interval hasn't elapsed yet (no work attempted this call). Otherwise
1086 returns {"checked": <rule count>, "moved": <total records moved>,
1087 "rules": [{"collection", "field", "from", "to", "moved"}, ...]} --
1088 mainly for tests and manual/CLI invocation, matching
1089 process_compactions' contract.
1090 """
1091 interval = _env_int(AUTO_TRANSITION_INTERVAL_SECONDS_ENV, _DEFAULT_AUTO_TRANSITION_INTERVAL_SECONDS)
1092 marker_path = Path(base_dir) / AUTO_TRANSITION_MARKER_NAME
1093 now = time.time()
1094 try:
1095 last_run = marker_path.stat().st_mtime
1096 except OSError:
1097 last_run = 0.0
1098
1099 if now - last_run < interval:
1100 return None
1101
1102 marker_path.parent.mkdir(parents=True, exist_ok=True)
1103 marker_path.write_text(str(now))
1104
1105 rules = auto_transition_rules_from_env()
1106 rule_results = []
1107 total_moved = 0
1108 for rule in rules:
1109 try:
1110 moved = _apply_auto_transition_rule(rule, base_dir=base_dir)
1111 except Exception as e:
1112 log(
1113 f"Auto-transition: rule {rule['collection']}.{rule['field']} "
1114 f"'{rule['from']}'->'{rule['to']}' failed: {e}",
1115 "ERROR",
1116 )
1117 moved = 0
1118 total_moved += moved
1119 rule_results.append({
1120 "collection": rule["collection"],
1121 "field": rule["field"],
1122 "from": rule["from"],
1123 "to": rule["to"],
1124 "moved": moved,
1125 })
1126
1127 log(f"Auto-transition: checked {len(rules)} rule(s), moved {total_moved} record(s)")
1128 return {"checked": len(rules), "moved": total_moved, "rules": rule_results}
1129
1130
1131# --- Rollups ---
1132
1133def process_rollups(*, base_dir: Path | str = "data") -> dict | None:
1134 """Recompute every due, enabled rollup_definitions row.
1135
1136 Rides this daemon's existing poll loop as one more pass
1137 (plan/vocabulary/14-rollup-spec.md's Dependencies: "No new daemon...
1138 process_rollups, alongside process_compactions"), but its due-gate is
1139 NOT the marker-file pattern process_compactions/process_stale_
1140 transitions use above: 14 is explicit that a rollup_definitions row
1141 already IS the natural place to hold that state (last_computed_at),
1142 unlike compaction's collection-wide pass, which has no equivalent
1143 per-collection record. So there's no marker file here and no fixed
1144 poll interval either -- each ENABLED definition is checked against
1145 its own last_computed_at/refresh_interval_seconds every call
1146 (object_rollups.is_definition_due), which is cheap (a timestamp
1147 comparison) for every definition that isn't due yet.
1148
1149 Returns None when the block-wide `rollup_enabled` flag is off (14's
1150 Degradation: "the daemon's rollup pass is skipped entirely; existing
1151 target collections keep serving their last-computed data") or when
1152 the rollup_definitions collection doesn't exist yet (package not
1153 installed). Otherwise returns {"checked": <definitions considered>,
1154 "computed": [{"definition_id", "target_collection", "groups",
1155 "suppressed", ...}, ...]} -- computed only lists definitions that
1156 were actually due and enabled; a skipped/disabled/not-yet-due
1157 definition doesn't appear.
1158
1159 Every definition's recompute is wrapped in its own try/except, same
1160 isolation pattern as process_compactions: one definition with a bad
1161 filter, a missing source collection, or a lock contention is logged
1162 and skipped, every other definition's pass proceeds.
1163 """
1164 if not object_rollups.rollup_pass_enabled(base_dir=base_dir):
1165 return None
1166
1167 try:
1168 definitions = object_records.read_collection_records(
1169 object_rollups.ROLLUP_DEFINITIONS_COLLECTION, base_dir=base_dir
1170 )
1171 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError):
1172 return None
1173
1174 now = datetime.now(timezone.utc)
1175 computed = []
1176 for definition in definitions:
1177 definition_id = definition.get("id") or "<unknown>"
1178
1179 if not object_rollups.is_definition_enabled(definition):
1180 continue
1181 if not object_rollups.is_definition_due(definition, now=now):
1182 continue
1183
1184 try:
1185 result = object_rollups.compute_rollup(definition, base_dir=base_dir)
1186 except Exception as e:
1187 log(f"Rollup: {definition_id} failed: {e}", "ERROR")
1188 continue
1189
1190 try:
1191 object_records.update_collection_record(
1192 object_rollups.ROLLUP_DEFINITIONS_COLLECTION,
1193 definition_id,
1194 {"last_computed_at": result["computed_at"]},
1195 base_dir=base_dir,
1196 actor=object_rollups.ROLLUP_ACTOR,
1197 preserve_read_only=True,
1198 )
1199 except Exception as e:
1200 # The recompute itself already succeeded and is live in the
1201 # target collection; failing to stamp last_computed_at only
1202 # means this definition looks "due" again next call (a
1203 # harmless, self-correcting re-run), never lost or corrupted
1204 # data -- logged, not fatal to the rest of the pass.
1205 log(f"Rollup: {definition_id} computed but failed to stamp last_computed_at: {e}", "ERROR")
1206
1207 log(
1208 f"Rollup: {definition_id} -> {result['target_collection']} "
1209 f"({result['groups']} group(s), {result['suppressed']} suppressed)"
1210 )
1211 computed.append(result)
1212
1213 return {"checked": len(definitions), "computed": computed}
1214
1215
1216# --- Materialize ---
1217
1218def process_materializations(*, base_dir: Path | str = "data") -> dict | None:
1219 """Generate every due, enabled, non-blocked scheduled/scheduled_fixed
1220 materialize_definitions row's output.
1221
1222 Rides this daemon's existing poll loop as one more pass
1223 (plan/vocabulary/61-materialize-spec.md's Dependencies: "No new
1224 daemon... process_materializations, alongside process_compactions").
1225 Unlike process_rollups (whose due-gate lives entirely on the
1226 definition row, no marker file needed), 61's Events section asks for
1227 process_stale_transitions' marker-file-gated shape instead -- gated by
1228 DBBASIC_MATERIALIZE_INTERVAL_SECONDS (default 3600), marker file
1229 `.materialize_last_run` under `base_dir`, surviving a daemon restart
1230 the same way every other marker-gated pass does.
1231
1232 Event-mode definitions (trigger.mode == "event") are never driven by
1233 this pass -- in v1 they run via materialize_run's manual path only
1234 (degrade-to-manual, per 61's Degradation section). The automatic
1235 on-create dispatch (materialize_seed's HANDLES) is deliberately NOT
1236 auto-wired: this pass does not rewrite materialize_seed's source to
1237 track the definition set. Rewriting an installed object at runtime --
1238 and doing it every poll -- is the wrong shape (expensive, surprising,
1239 self-modifying code); if auto-synced HANDLES is ever wanted it belongs
1240 in a deliberate scheduled job with its own tests, not the poll loop.
1241 materialize_seed ships inert (HANDLES == []); the event-dispatch logic
1242 it would call still exists and is tested, ready for that future
1243 mechanism or a manual wiring.
1244
1245 For each enabled, non-blocked, due scheduled/scheduled_fixed
1246 definition: object_materialize.generate_definition reads
1247 source_collection outside row-filters (daemon posture, same as
1248 compaction/rollup/auto-transition), computes the due (source row,
1249 period) set from first principles every call (never trusting a
1250 row's own next_run/last_run as the correctness mechanism -- see that
1251 module's docstring), and for each checks the deterministic header id
1252 in output_collection: missing -> generate, present -> skip, not an
1253 error.
1254
1255 Two-level isolation, per 61's Events section (drawn from process_
1256 stale_transitions' _apply_auto_transition_rule, not process_rollups'
1257 per-definition-only isolation): one bad DEFINITION (a malformed
1258 mapping, a missing source/output/child collection) is caught here and
1259 never stops any other definition; one bad SOURCE ROW within an
1260 otherwise-good definition is caught inside object_materialize.
1261 generate_config and surfaces as one entry in that definition's own
1262 "errors" list, never stopping any other row in the same definition.
1263
1264 A missing source/output/child collection is logged once per process
1265 (object_materialize.MissingCollectionError, warned-once via
1266 _WARNED_UNKNOWN_MATERIALIZE_COLLECTIONS) -- mirrors process_stale_
1267 transitions' _WARNED_UNKNOWN_AUTO_TRANSITION_COLLECTIONS exactly, to
1268 avoid re-logging every poll interval.
1269
1270 Always logs exactly one summary line per run, even a no-op run
1271 (`"Materialize: checked N definition(s), generated M record(s),
1272 skipped K already-generated"`) -- every sibling pass's "activity or
1273 deliberate silence is visible in the daemon log" convention.
1274
1275 Returns None when the block-wide `materialize_enabled` flag is off,
1276 the materialize_definitions collection doesn't exist yet (package not
1277 installed), or the interval hasn't elapsed. Otherwise returns
1278 {"checked": <definitions considered>, "generated": <total records>,
1279 "skipped_already_generated": <total>, "results": [...]}.
1280 """
1281 if not object_materialize.materialize_pass_enabled(base_dir=base_dir):
1282 return None
1283
1284 interval = _env_int(MATERIALIZE_INTERVAL_SECONDS_ENV, _DEFAULT_MATERIALIZE_INTERVAL_SECONDS)
1285 marker_path = Path(base_dir) / MATERIALIZE_MARKER_NAME
1286 now_ts = time.time()
1287 try:
1288 last_run = marker_path.stat().st_mtime
1289 except OSError:
1290 last_run = 0.0
1291
1292 if now_ts - last_run < interval:
1293 return None
1294
1295 try:
1296 definitions = object_records.read_collection_records(
1297 object_materialize.MATERIALIZE_DEFINITIONS_COLLECTION, base_dir=base_dir
1298 )
1299 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError):
1300 return None
1301
1302 marker_path.parent.mkdir(parents=True, exist_ok=True)
1303 marker_path.write_text(str(now_ts))
1304
1305 now = datetime.now(timezone.utc)
1306 total_generated = 0
1307 total_skipped = 0
1308 results = []
1309
1310 for definition in definitions:
1311 definition_id = definition.get("id") or "<unknown>"
1312
1313 if object_materialize.is_definition_blocked(definition):
1314 continue
1315 if not object_materialize.is_definition_enabled(definition):
1316 continue
1317 if not object_materialize.is_definition_due(definition, now=now):
1318 continue
1319
1320 try:
1321 config = object_materialize.parse_definition(definition, base_dir=base_dir)
1322 except object_materialize.MissingCollectionError as e:
1323 if definition_id not in _WARNED_UNKNOWN_MATERIALIZE_COLLECTIONS:
1324 log(
1325 f"Materialize: {definition_id} references missing {e.role} collection "
1326 f"'{e.collection}' (package not installed?), skipping -- will keep "
1327 "checking, logged once",
1328 "WARN",
1329 )
1330 _WARNED_UNKNOWN_MATERIALIZE_COLLECTIONS.add(definition_id)
1331 continue
1332 except Exception as e:
1333 log(f"Materialize: {definition_id} failed: {e}", "ERROR")
1334 continue
1335
1336 if config.trigger_mode == "event":
1337 continue # event-mode definitions are driven by dispatch/manual only
1338
1339 _WARNED_UNKNOWN_MATERIALIZE_COLLECTIONS.discard(definition_id)
1340
1341 try:
1342 result = object_materialize.generate_config(config, base_dir=base_dir, now=now)
1343 except Exception as e:
1344 log(f"Materialize: {definition_id} failed: {e}", "ERROR")
1345 continue
1346
1347 for error in result["errors"]:
1348 log(
1349 f"Materialize: {definition_id} source={error['source_id']} "
1350 f"period={error['period_start']} failed: {error['error']}",
1351 "ERROR",
1352 )
1353
1354 try:
1355 object_records.update_collection_record(
1356 object_materialize.MATERIALIZE_DEFINITIONS_COLLECTION,
1357 definition_id,
1358 {"last_run_at": _now_iso_utc()},
1359 base_dir=base_dir,
1360 actor=config.actor,
1361 preserve_read_only=True,
1362 )
1363 except Exception as e:
1364 # The generation itself already succeeded (whatever was due is
1365 # live in output_collection); failing to stamp last_run_at only
1366 # means this definition looks "due" again next call -- a
1367 # harmless, self-correcting re-run (the deterministic header id
1368 # is still the real gate), never lost or corrupted data.
1369 log(f"Materialize: {definition_id} ran but failed to stamp last_run_at: {e}", "ERROR")
1370
1371 total_generated += result["generated"]
1372 total_skipped += result["skipped_already_generated"]
1373 results.append(result)
1374
1375 log(
1376 f"Materialize: checked {len(definitions)} definition(s), generated "
1377 f"{total_generated} record(s), skipped {total_skipped} already-generated"
1378 )
1379 return {
1380 "checked": len(definitions),
1381 "generated": total_generated,
1382 "skipped_already_generated": total_skipped,
1383 "results": results,
1384 }
1385
1386
1387def _now_iso_utc() -> str:
1388 return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
1389
1390
1391# --- Object Execution ---
1392
1393def _execute_target(runtime: ObjectRuntime, object_id: str, method: str, payload: dict):
1394 """Load and execute a target object."""
1395 request = ObjectExecutionRequest(object_id=object_id, method=method, payload=payload)
1396 result = execute_object(runtime, request)
1397 if not result.ok:
1398 if result.error and result.error.type == "ObjectNotFoundError":
1399 raise FileNotFoundError(result.error.message)
1400 raise ObjectExecutionFailure(result)
1401 return result.result
1402
1403
1404def _find_object_file(object_id: str) -> Path | None:
1405 """Find the .py file for an object ID."""
1406 return resolve_object_id(object_id)
1407
1408
1409def process_notifications(*, base_dir: Path | str = "data") -> dict | None:
1410 """12 notify: turn new record-change events into notifications.
1411
1412 Polls the record-change log rather than riding synchronous HANDLES
1413 dispatch -- HANDLES is gated behind DBBASIC_ENABLE_EVENT_HANDLERS (off in
1414 prod) and we deliberately don't rewrite installed objects to track dynamic
1415 event sets (see object_notify's docstring). Reads each watched collection's
1416 change entries newer than the cursor, matches them against enabled
1417 notify_rules (object_notify), and appends a notifications row per resolved
1418 recipient. At-least-once: a crash between writing a notification and
1419 advancing the cursor re-notifies, the delivery bar 12/01 accept.
1420
1421 Returns None when notify is disabled or there are no rules; otherwise
1422 {"changes": <processed>, "notifications": <written>}.
1423 """
1424 if not object_notify.notify_pass_enabled(base_dir=base_dir):
1425 return None
1426 try:
1427 rules = object_records.read_collection_records(
1428 object_notify.NOTIFY_RULES_COLLECTION, base_dir=base_dir
1429 )
1430 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError):
1431 return None
1432 enabled = [r for r in rules if str(r.get("enabled", "true")).strip().lower() not in {"off", "false", "0", "no"}]
1433 if not enabled:
1434 return None
1435
1436 cursor_path = Path(base_dir) / NOTIFY_CURSOR_NAME
1437 now_iso = datetime.now(timezone.utc).isoformat()
1438 try:
1439 cursor = cursor_path.read_text().strip()
1440 except OSError:
1441 cursor = ""
1442 if not cursor:
1443 # First run: stamp at now, notify only on FUTURE changes (never
1444 # backfill the entire history).
1445 cursor_path.parent.mkdir(parents=True, exist_ok=True)
1446 cursor_path.write_text(now_iso)
1447 return None
1448
1449 try:
1450 known = {c.get("name") for c in object_collections.list_collections(base_dir=base_dir) if c.get("name")}
1451 except (OSError, ValueError):
1452 known = set()
1453 watched = object_notify.watched_collections(enabled, known)
1454
1455 # Gather every change newer than the cursor, across watched collections.
1456 fresh: list[dict] = []
1457 for collection in watched:
1458 try:
1459 payload = object_record_changes.list_record_changes(collection, base_dir=base_dir, limit=1000)
1460 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError, OSError, ValueError):
1461 continue
1462 for change in payload.get("changes") or []:
1463 ts = str(change.get("timestamp") or "")
1464 if ts > cursor:
1465 fresh.append(change)
1466 fresh.sort(key=lambda c: str(c.get("timestamp") or ""))
1467
1468 written = 0
1469 emailed = 0
1470 max_ts = cursor
1471 for change in fresh:
1472 # Per-change try/except: one malformed rule or change never stops the
1473 # rest, and the cursor still advances past it (never re-storming).
1474 try:
1475 for rule in enabled:
1476 for note in object_notify.notifications_for_change(rule, change, base_dir=base_dir):
1477 object_records.create_collection_record(
1478 object_notify.NOTIFICATIONS_COLLECTION, note,
1479 base_dir=base_dir, actor=object_notify.DEFAULT_ACTOR,
1480 )
1481 written += 1
1482 # The email channel rides the GENERIC 01 outbox (object_email),
1483 # never the private mail package -- notify depends only on the
1484 # open adapter; whatever SMTP relay is configured delivers it.
1485 for intent in object_notify.email_intents_for_change(rule, change, base_dir=base_dir):
1486 if _enqueue_notify_email(intent, base_dir=base_dir):
1487 emailed += 1
1488 except Exception as exc: # noqa: BLE001 -- isolate one bad change
1489 log(f"Notify: change {change.get('change_id')} failed: {exc}", "ERROR")
1490 ts = str(change.get("timestamp") or "")
1491 if ts > max_ts:
1492 max_ts = ts
1493
1494 if max_ts != cursor:
1495 cursor_path.write_text(max_ts)
1496 if fresh or written or emailed:
1497 log(f"Notify: processed {len(fresh)} change(s), wrote {written} notification(s), queued {emailed} email(s)")
1498 return {"changes": len(fresh), "notifications": written, "emails": emailed}
1499
1500
1501def _enqueue_notify_email(intent: dict, *, base_dir: Path | str) -> bool:
1502 """Map a notify email intent's user_id to an address and enqueue it into the
1503 generic 01 outbox. Returns False (skips) when the user has no address on
1504 file or the email_outbox isn't installed -- email is best-effort, never
1505 blocks the in_app write."""
1506 try:
1507 user = object_identity.get_user(intent["user_id"], base_dir=base_dir)
1508 except (object_identity.UserNotFoundError, OSError, ValueError):
1509 return False
1510 address = (user.get("email") or "").strip()
1511 if not address:
1512 return False
1513 try:
1514 object_email.enqueue(
1515 address, intent.get("subject") or "", intent.get("body") or "",
1516 source_object_id="notify",
1517 extra={"user_id": intent["user_id"], "target": intent.get("target", "")},
1518 base_dir=base_dir,
1519 )
1520 except (object_collections.CollectionNotFoundError,
1521 object_collections.InvalidCollectionNameError):
1522 return False # app-email not installed -> email delivery unavailable
1523 return True
1524
1525
1526# 01 email adapter: rolling per-minute send-rate window, persisted as JSON
1527# ({window_start, sent_count}) so it survives a daemon restart -- the same
1528# "cheap state outside the collection" shape process_compactions' marker uses.
1529EMAIL_RATE_MARKER_NAME = ".email_rate_window"
1530# Whether we've already logged "SMTP not configured" this process. The pass
1531# runs every tick (it's one cheap collection read) but must not repeat the
1532# line every poll -- matching process_scheduler/process_queue when their own
1533# trigger object is absent.
1534_EMAIL_UNCONFIGURED_WARNED = False
1535
1536
1537def _read_email_rate_window(base_dir: Path | str) -> dict | None:
1538 try:
1539 return json.loads((Path(base_dir) / EMAIL_RATE_MARKER_NAME).read_text())
1540 except (OSError, ValueError):
1541 return None
1542
1543
1544def _write_email_rate_window(base_dir: Path | str, window: dict) -> None:
1545 path = Path(base_dir) / EMAIL_RATE_MARKER_NAME
1546 path.parent.mkdir(parents=True, exist_ok=True)
1547 path.write_text(json.dumps(window))
1548
1549
1550def process_email_outbox(*, base_dir: Path | str = "data") -> dict | None:
1551 """01 email adapter: drain the email_outbox queue.
1552
1553 Every tick, delivers the `queued` rows that are due (`next_attempt_at`
1554 arrived) up to DBBASIC_SMTP_BATCH_SIZE, bounded by a rolling per-minute
1555 rate window. Each send's outcome is written back onto its row: `sent`, or
1556 `queued` again with a backed-off `next_attempt_at` and `last_error` (a
1557 transient failure), or `dead` (a permanent SMTP error, or retries
1558 exhausted). Per-message try/except -- one bad send never blocks the batch,
1559 matching process_compactions' per-item isolation.
1560
1561 Returns None when email is disabled (feature flag), unconfigured (no SMTP
1562 mode / host -- everything just keeps queuing, fully inspectable), or the
1563 email_outbox collection isn't installed. Otherwise a small summary dict.
1564 """
1565 global _EMAIL_UNCONFIGURED_WARNED
1566 if not object_email.email_pass_enabled(base_dir=base_dir):
1567 return None
1568
1569 config = object_email.smtp_config_from_env()
1570 if not config.configured:
1571 if not _EMAIL_UNCONFIGURED_WARNED:
1572 log("Email: SMTP not configured (DBBASIC_SMTP_MODE) -- outbound mail is queuing only")
1573 _EMAIL_UNCONFIGURED_WARNED = True
1574 return None
1575 _EMAIL_UNCONFIGURED_WARNED = False # configured again -> re-warn if it flips back
1576
1577 try:
1578 records = object_records.read_collection_records(
1579 object_email.OUTBOX_COLLECTION, base_dir=base_dir
1580 )
1581 except (object_collections.CollectionNotFoundError,
1582 object_collections.InvalidCollectionNameError, OSError, ValueError):
1583 return None
1584
1585 now = datetime.now(timezone.utc)
1586 due = [r for r in records if object_email.is_due(r, now)]
1587 if not due:
1588 return {"attempted": 0, "sent": 0, "dead": 0}
1589 # Oldest-scheduled first, so a backlog drains fairly rather than starving
1590 # the earliest-queued behind newer arrivals.
1591 due.sort(key=lambda r: (str(r.get("next_attempt_at") or ""), str(r.get("created_at") or "")))
1592
1593 window = object_email.rate_window_reset(_read_email_rate_window(base_dir), time.time())
1594 sender = object_email.sender_for(config)
1595 attempted = sent = dead = rate_limited = 0
1596
1597 for record in due[:config.batch_size]:
1598 if window["sent_count"] >= config.rate_limit:
1599 rate_limited += 1
1600 continue # left `queued`; a scheduling skip is not a delivery attempt
1601 try:
1602 update = object_email.attempt_delivery(record, config, sender=sender, now=now)
1603 except Exception as exc: # noqa: BLE001 -- isolate one bad message
1604 log(f"Email: message {record.get('id')} delivery raised: {exc}", "ERROR")
1605 continue
1606 window["sent_count"] += 1 # a network attempt was made (success or not)
1607 attempted += 1
1608 try:
1609 object_records.update_collection_record(
1610 object_email.OUTBOX_COLLECTION, record["id"], update,
1611 base_dir=base_dir, actor=object_email.DEFAULT_ACTOR,
1612 preserve_read_only=True,
1613 )
1614 except Exception as exc: # noqa: BLE001
1615 # The send already happened; failing to record the outcome only
1616 # risks an at-least-once re-send next tick -- the delivery bar 01
1617 # accepts, never lost data.
1618 log(f"Email: message {record.get('id')} sent but status write failed: {exc}", "ERROR")
1619 if update.get("status") == object_email.STATUS_SENT:
1620 sent += 1
1621 elif update.get("status") == object_email.STATUS_DEAD:
1622 dead += 1
1623
1624 _write_email_rate_window(base_dir, window)
1625 if attempted or rate_limited:
1626 extra = f", {rate_limited} rate-limited" if rate_limited else ""
1627 log(f"Email: attempted {attempted} ({sent} sent, {dead} dead){extra}")
1628 return {"attempted": attempted, "sent": sent, "dead": dead, "rate_limited": rate_limited}
1629
1630
1631CHANGE_LOG_RETENTION_MARKER_NAME = ".change_log_retention_last_run"
1632CHANGE_LOG_RETENTION_INTERVAL_ENV = "DBBASIC_CHANGE_LOG_RETENTION_INTERVAL_SECONDS"
1633_DEFAULT_CHANGE_LOG_RETENTION_INTERVAL = 21600 # 6h -- rewriting every log is not cheap
1634
1635
1636def process_change_log_retention(*, base_dir: Path | str = "data") -> dict | None:
1637 """Rotate, archive and (only if asked) remove record change logs.
1638
1639 Returns None when no policy is configured or the pass is not due.
1640 Off unless an operator sets a retention window or an entry cap: a
1641 change log IS the audit trail, and deciding how much of it to keep is
1642 not a decision a daemon makes on somebody's behalf.
1643
1644 When it IS configured, expired entries are ARCHIVED by default rather
1645 than deleted -- rotated into a timestamped gzip segment beside the log
1646 (object_record_changes.prune_all_record_changes). Somebody asking for
1647 a smaller hot file has not asked to lose the history, and the hot file
1648 is the only part that costs anything: it is what every feed render
1649 reads. On the box that motivated this, 1.1GB of logs became 22MB hot
1650 plus a 115MB archive with all 1.7 million entries still in it.
1651
1652 Runs on a 6h marker, the same shape as the analytics retention pass,
1653 because rewriting every collection's log is not something to do on a
1654 tick -- the first live sweep took three minutes.
1655 """
1656 policy = object_record_changes.retention_policy()
1657 if not policy["days"] and not policy["max_entries"]:
1658 return None
1659
1660 marker_path = Path(base_dir) / CHANGE_LOG_RETENTION_MARKER_NAME
1661 interval = _env_int(CHANGE_LOG_RETENTION_INTERVAL_ENV,
1662 _DEFAULT_CHANGE_LOG_RETENTION_INTERVAL)
1663 now = time.time()
1664 try:
1665 if now - marker_path.stat().st_mtime < interval:
1666 return None
1667 except OSError:
1668 pass # no marker yet -> run now
1669 marker_path.parent.mkdir(parents=True, exist_ok=True)
1670 marker_path.write_text(str(now))
1671
1672 try:
1673 result = object_record_changes.prune_all_record_changes(
1674 base_dir=base_dir,
1675 days=policy["days"],
1676 max_entries=policy["max_entries"],
1677 archive=policy["archive"],
1678 keep_archives=policy["keep_archives"],
1679 )
1680 except OSError:
1681 return None
1682 if result.get("removed"):
1683 verb = "archived" if policy["archive"] else "removed"
1684 log(f"Change logs: {verb} {result['removed']} entr(ies) across "
1685 f"{result['collections']} log(s)")
1686 return result
1687
1688
1689RESTORE_POINT_RETENTION_MARKER_NAME = ".restore_point_retention_last_run"
1690RESTORE_POINT_RETENTION_INTERVAL_ENV = "DBBASIC_RESTORE_POINT_RETENTION_INTERVAL_SECONDS"
1691RESTORE_POINT_KEEP_LAST_ENV = "DBBASIC_RESTORE_POINT_KEEP_LAST"
1692RESTORE_POINT_KEEP_DAYS_ENV = "DBBASIC_RESTORE_POINT_KEEP_DAYS"
1693RESTORE_POINT_MAX_BYTES_ENV = "DBBASIC_RESTORE_POINT_MAX_BYTES"
1694_DEFAULT_RESTORE_POINT_INTERVAL = 21600 # 6h, like the other sweeps
1695_DEFAULT_RESTORE_POINT_KEEP_LAST = 20
1696_DEFAULT_RESTORE_POINT_KEEP_DAYS = 7
1697
1698
1699def process_restore_point_retention(*, base_dir: Path | str = "data") -> dict | None:
1700 """Sweep AUTOMATIC restore points. Never touches a manual backup.
1701
1702 ON BY DEFAULT, which is the opposite of the change-log pass above, and
1703 the difference is who asked for the files. A change log IS the audit
1704 trail, so how much to keep is not a decision a daemon makes on
1705 somebody's behalf. Restore points are scaffolding the server writes for
1706 itself before every package install -- nobody asked for them, and the
1707 hundredth-oldest one from three weeks ago is worth nothing.
1708
1709 The box that motivated this had 157 of them at ~91MB, 14.3GB against
1710 4.0GB free, on a machine also serving production, with 93 written in
1711 the preceding two days. Left alone it fills the disk in about a day,
1712 and a full disk on that box takes production down with it. That is the
1713 fourth time this shape of bug has appeared here (page_views, restore
1714 points, change logs, restore points again).
1715
1716 Keeps the newest DBBASIC_RESTORE_POINT_KEEP_LAST (default 20) and
1717 anything younger than DBBASIC_RESTORE_POINT_KEEP_DAYS (default 7), so
1718 a burst of installs in one afternoon cannot evict the morning's safety
1719 net. Setting KEEP_LAST to 0 does NOT disable the sweep -- the floor is
1720 object_backup_index.MIN_KEEP -- because sweeping to the bone would
1721 remove the very safety net this feature exists to provide.
1722
1723 The BUDGET (DBBASIC_RESTORE_POINT_MAX_BYTES, default 2GB) is what
1724 actually bounds the disk, and it outranks the window. A first cut of
1725 this pass had only a count and an age window; a dry run on the real box
1726 freed 78MB of 14.3GB, because 93 archives were two days old and the
1727 window protected them all. Count and age cannot bound bytes.
1728 """
1729 marker_path = Path(base_dir) / RESTORE_POINT_RETENTION_MARKER_NAME
1730 interval = _env_int(RESTORE_POINT_RETENTION_INTERVAL_ENV,
1731 _DEFAULT_RESTORE_POINT_INTERVAL)
1732 now = time.time()
1733 try:
1734 if now - marker_path.stat().st_mtime < interval:
1735 return None
1736 except OSError:
1737 pass # no marker yet -> run now
1738 marker_path.parent.mkdir(parents=True, exist_ok=True)
1739 marker_path.write_text(str(now))
1740
1741 try:
1742 result = object_backup_index.prune_backups(
1743 data_dir=base_dir,
1744 keep_last=_env_int(RESTORE_POINT_KEEP_LAST_ENV,
1745 _DEFAULT_RESTORE_POINT_KEEP_LAST),
1746 keep_newer_than_days=_env_int(RESTORE_POINT_KEEP_DAYS_ENV,
1747 _DEFAULT_RESTORE_POINT_KEEP_DAYS),
1748 max_total_bytes=_env_int(
1749 RESTORE_POINT_MAX_BYTES_ENV,
1750 object_backup_index.DEFAULT_MAX_TOTAL_BYTES),
1751 )
1752 except OSError:
1753 return None
1754 if result.get("removed"):
1755 freed_mb = int(result["freed_bytes"]) // (1024 * 1024)
1756 log(f"Restore points: removed {result['removed']} archive(s), "
1757 f"freed {freed_mb}MB, kept {result['kept']} "
1758 f"(+{result['protected']} manual, never swept)")
1759 for problem in result.get("errors") or []:
1760 log(f"Restore points: could not remove {problem}", "ERROR")
1761 return result
1762
1763
1764def _log_backup_outcome(kind: str, outcome: dict) -> None:
1765 """The daemon's line for a finished scheduled backup or restore test.
1766 A failure is an ERROR line naming why; a backup whose restore test
1767 failed is an ERROR too, never an INFO line that happens to mention it."""
1768 if kind == "backup":
1769 if not outcome.get("ok"):
1770 log(f"Backup: FAILED: {outcome.get('error')}", "ERROR")
1771 return
1772 test = outcome.get("restore_test") or {}
1773 line = (f"Backup: {outcome.get('name')} -- {outcome.get('files')} file(s), "
1774 f"{object_backup_schedule._mb(outcome.get('bytes'))} "
1775 f"({outcome.get('linked')} linked, {outcome.get('copied')} copied, "
1776 f"{object_backup_schedule._mb(outcome.get('copied_bytes'))} written) "
1777 f"in {outcome.get('total_seconds')}s")
1778 if outcome.get("pruned"):
1779 line += f"; pruned {len(outcome['pruned'])} old snapshot(s)"
1780 if test.get("ok"):
1781 log(line + "; restore test ok")
1782 else:
1783 log(line + f"; restore test FAILED: {'; '.join(test.get('errors') or [])}", "ERROR")
1784 for warning in outcome.get("warnings") or []:
1785 log(f"Backup: {warning}", "WARN")
1786 after = outcome.get("after_command") or {}
1787 if after and not after.get("ok"):
1788 log(f"Backup: after-command FAILED: {after.get('error')}", "ERROR")
1789 return
1790 if outcome.get("ok"):
1791 log(f"Backup restore test: {outcome.get('snapshot')} ok")
1792 else:
1793 log(f"Backup restore test: FAILED: "
1794 f"{'; '.join(outcome.get('errors') or [outcome.get('error') or 'unknown'])}", "ERROR")
1795
1796
1797def process_scheduled_backup(*, base_dir: Path | str = "data", objects_dir=None):
1798 """Start a scheduled backup when one is due; return its thread or None.
1799
1800 OFF unless DBBASIC_BACKUP_DESTINATION names a destination
1801 (object_backup_schedule has the why of everything else). On a thread,
1802 because copying a large box takes minutes and the scheduler, queue and
1803 event passes must not stop for it -- the one thing worse than no backup
1804 is a backup that silently stalls the invoices. One run at a time per
1805 process (start_in_background) and per destination (its flock), so the
1806 server's "back up now" and this pass cannot collide.
1807 """
1808 if not object_backup_schedule.due(base_dir):
1809 return None
1810 return object_backup_schedule.start_in_background(
1811 "backup", base_dir, objects_dir=objects_dir, on_done=_log_backup_outcome)
1812
1813
1814ANALYTICS_RETENTION_MARKER_NAME = ".analytics_retention_last_run"
1815ANALYTICS_RETENTION_INTERVAL_ENV = "DBBASIC_ANALYTICS_RETENTION_INTERVAL_SECONDS"
1816_DEFAULT_ANALYTICS_RETENTION_INTERVAL = 21600 # 6h -- a rewrite of a big file isn't cheap
1817
1818
1819def process_analytics_retention(*, base_dir: Path | str = "data") -> dict | None:
1820 """Age page_views rows out past the retention window, bounding the file.
1821
1822 page_views is the platform's heaviest write path and a pure event log --
1823 id-fold compaction can't shrink it (nothing is superseded), so retention is
1824 a time-windowed rewrite (object_records.prune_collection_records). Gated by
1825 a marker file + interval (default 6h), the same shape process_compactions
1826 uses -- a rewrite of a massive file is not something to do every tick.
1827
1828 Returns None when disabled/not-due/not-installed; else the prune summary.
1829 """
1830 if not object_analytics.analytics_enabled():
1831 return None
1832
1833 marker_path = Path(base_dir) / ANALYTICS_RETENTION_MARKER_NAME
1834 interval = _env_int(ANALYTICS_RETENTION_INTERVAL_ENV, _DEFAULT_ANALYTICS_RETENTION_INTERVAL)
1835 now = time.time()
1836 try:
1837 if now - marker_path.stat().st_mtime < interval:
1838 return None
1839 except OSError:
1840 pass # no marker yet -> run now
1841 marker_path.parent.mkdir(parents=True, exist_ok=True)
1842 marker_path.write_text(str(now))
1843
1844 days = object_analytics.retention_days()
1845 cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat().replace("+00:00", "Z")
1846 cap = object_analytics.max_rows()
1847 try:
1848 result = object_records.prune_collection_records(
1849 object_analytics.PAGE_VIEWS_COLLECTION,
1850 keep_newer_than=cutoff, timestamp_field="created_at",
1851 # Two bounds, because a retention window says how far back to
1852 # keep and nothing at all about how much can arrive inside it.
1853 keep_last=(cap or None),
1854 base_dir=base_dir,
1855 )
1856 except (object_collections.CollectionNotFoundError,
1857 object_collections.InvalidCollectionNameError, OSError, ValueError):
1858 return None
1859 if result.get("pruned"):
1860 bound = f"older than {days}d" + (f" or beyond {cap} rows" if cap else "")
1861 log(f"Analytics: pruned {result['removed']} page_view(s) {bound} "
1862 f"({result['rows_before']} -> {result['rows_after']})")
1863 return result
1864
1865
1866ATTENTION_SOURCES_COLLECTION = "attention_sources"
1867ATTENTION_COUNTS_COLLECTION = "attention_counts"
1868ATTENTION_MARKER_NAME = ".attention_last_run"
1869ATTENTION_INTERVAL_ENV = "DBBASIC_ATTENTION_INTERVAL_SECONDS"
1870# Five minutes. A count that is five minutes stale is fine -- nobody
1871# confirms a receipt in the seconds after it lands -- and the page says
1872# how old the number is rather than implying it is live.
1873_DEFAULT_ATTENTION_INTERVAL = 300
1874ATTENTION_ACTOR = "daemon:attention"
1875ATTENTION_METHOD = "COUNT"
1876_ATTENTION_DETAIL_LIMIT = 200
1877_ATTENTION_ERROR_LIMIT = 400
1878_TRUE_TEXT = ("true", "1", "yes", "on")
1879
1880
1881def _attention_text(value) -> str:
1882 return str(value if value is not None else "").strip()
1883
1884
1885def _attention_count_value(answer) -> int:
1886 """The integer a provider promised, or a refusal to guess.
1887
1888 Raises ValueError rather than coercing, because every coercion here is
1889 a way for a broken provider to look like an empty queue. A provider
1890 that answers with a string, a float, a bool, or nothing at all has a
1891 bug, and the only useful thing to do with it is say so.
1892 """
1893 if not isinstance(answer, dict):
1894 raise ValueError(f"provider returned {type(answer).__name__}, expected an object")
1895 if "count" not in answer:
1896 raise ValueError("provider returned no 'count'")
1897 count = answer["count"]
1898 if isinstance(count, bool) or not isinstance(count, int):
1899 raise ValueError(f"provider returned a {type(count).__name__} count, expected an integer")
1900 if count < 0:
1901 raise ValueError(f"provider returned a negative count: {count}")
1902 return count
1903
1904
1905def process_attention(*, base_dir: Path | str = "data") -> dict | None:
1906 """Run every declared attention provider and write the counts down.
1907
1908 Packages declare what "needs a human" means in their own domain
1909 (object_packages' `attention` section -> the attention_sources
1910 collection). This pass executes each declaration's object with method
1911 COUNT -- a distinct verb, so the same object may also expose GET or
1912 POST for a person -- and stores the answer in attention_counts, which
1913 is the one small table the home page and the app list read.
1914
1915 **Why a rollup and not a live fold.** Because folding a dozen
1916 collections on every home render is how a home page becomes the
1917 slowest page, and worse than slow: this box went to 675MB resident and
1918 started swapping because something folded a big collection on a timer.
1919 A home screen that folds a dozen collections per render is that exact
1920 mistake with a nicer name -- and it makes the front page's cost grow
1921 with the number of installed packages, which is the one place cost
1922 must not grow. The pass is marker-gated (DBBASIC_ATTENTION_INTERVAL_
1923 SECONDS, default 300) like process_compactions and
1924 process_materializations, so the page's cost is one small read no
1925 matter how many apps declare a queue, and the staleness is bounded and
1926 stated rather than pretended away.
1927
1928 **A broken provider must look broken, never look calm.** A provider
1929 that raises, or answers with something that is not an integer, has its
1930 `error` written and its PREVIOUS count kept. Zeroing it would report
1931 an empty queue when what actually happened is that nobody looked, and
1932 a queue that looks handled is the single worst thing this table could
1933 say. `computed_at` is left at the last SUCCESSFUL run for the same
1934 reason: the age on the page should describe the number, not the
1935 attempt.
1936
1937 Zero counts are written and kept. The absence of a row means nobody
1938 has ever run the provider, which is a different fact from "the queue
1939 is empty", and only the surfaces decide that zeros are not news.
1940
1941 A source the operator muted is not executed at all, and its stored
1942 count is removed -- a muted queue should cost nothing and show
1943 nothing, and leaving the last number behind would show a stale one.
1944
1945 Returns None when the collection is not installed (app-nav absent) or
1946 the interval has not elapsed; otherwise a summary of the pass.
1947 """
1948 try:
1949 sources = object_records.read_collection_records(
1950 ATTENTION_SOURCES_COLLECTION, base_dir=base_dir)
1951 except (object_collections.CollectionNotFoundError,
1952 object_collections.InvalidCollectionNameError, OSError, ValueError):
1953 return None
1954 if not sources:
1955 return None
1956
1957 marker_path = Path(base_dir) / ATTENTION_MARKER_NAME
1958 interval = _env_int(ATTENTION_INTERVAL_ENV, _DEFAULT_ATTENTION_INTERVAL)
1959 now = time.time()
1960 try:
1961 if now - marker_path.stat().st_mtime < interval:
1962 return None
1963 except OSError:
1964 pass # no marker yet -> run now
1965 marker_path.parent.mkdir(parents=True, exist_ok=True)
1966 marker_path.write_text(str(now))
1967
1968 try:
1969 from python_object_runtime import PythonObjectRuntime
1970 except ImportError:
1971 return None
1972 runtime = PythonObjectRuntime(base_dir=str(base_dir))
1973
1974 try:
1975 existing = {row["id"]: row for row in object_records.read_collection_records(
1976 ATTENTION_COUNTS_COLLECTION, base_dir=base_dir) if row.get("id")}
1977 except (object_collections.CollectionNotFoundError,
1978 object_collections.InvalidCollectionNameError, OSError, ValueError):
1979 # The counts collection is what this pass exists to write. Without
1980 # it there is nowhere to put an answer, so there is no point
1981 # running any provider.
1982 return None
1983
1984 computed_at = datetime.now(timezone.utc).isoformat()
1985 counted = failed = muted = skipped_declared = 0
1986
1987 for source in sources:
1988 source_id = _attention_text(source.get("id"))
1989 if not source_id:
1990 continue
1991 live = existing.get(source_id)
1992
1993 # A declared count (`collection` + `where`, object_attention) is
1994 # counted for each viewer when it is shown, over the rows that
1995 # viewer may read, and never here: a number computed with no
1996 # viewer is exactly what it replaced. A row left by the provider it
1997 # replaced is removed like a muted one, because attention_counts is
1998 # readable by every signed-in user and that global number is not.
1999 declared = bool(_attention_text(source.get("collection")))
2000 if declared:
2001 skipped_declared += 1
2002 if declared or _attention_text(source.get("operator_muted")).lower() in _TRUE_TEXT:
2003 if not declared:
2004 muted += 1
2005 if live is not None:
2006 try:
2007 object_records.delete_collection_record(
2008 ATTENTION_COUNTS_COLLECTION, source_id,
2009 base_dir=base_dir, actor=ATTENTION_ACTOR)
2010 except Exception: # noqa: BLE001 -- a stuck row must not stop the pass
2011 pass
2012 continue
2013
2014 row = {
2015 "source_id": source_id,
2016 "label": _attention_text(source.get("label")),
2017 "path": _attention_text(source.get("path")),
2018 "nav_id": _attention_text(source.get("nav_id")),
2019 "group": _attention_text(source.get("group")) or "Apps",
2020 "severity": _attention_text(source.get("severity")) or "normal",
2021 }
2022
2023 object_id = _attention_text(source.get("object_id"))
2024 try:
2025 answer = _execute_target(runtime, object_id, ATTENTION_METHOD, {})
2026 count = _attention_count_value(answer)
2027 except Exception as exc: # noqa: BLE001 -- one bad provider must not blind the rest
2028 failed += 1
2029 log(f"Attention: {source_id} ({object_id}) failed: {exc}", "ERROR")
2030 row["error"] = f"{type(exc).__name__}: {exc}"[:_ATTENTION_ERROR_LIMIT]
2031 # The previous number survives, and so does its timestamp: an
2032 # unanswered question is not the answer zero.
2033 row["count"] = _attention_text((live or {}).get("count")) or "0"
2034 row["detail"] = _attention_text((live or {}).get("detail"))
2035 row["computed_at"] = _attention_text((live or {}).get("computed_at"))
2036 else:
2037 counted += 1
2038 row["count"] = str(count)
2039 row["detail"] = _attention_text(answer.get("detail"))[:_ATTENTION_DETAIL_LIMIT]
2040 row["error"] = ""
2041 row["computed_at"] = computed_at
2042
2043 try:
2044 if live is None:
2045 object_records.create_collection_record(
2046 ATTENTION_COUNTS_COLLECTION, {"id": source_id, **row},
2047 base_dir=base_dir, actor=ATTENTION_ACTOR)
2048 elif any(_attention_text(live.get(field)) != row[field] for field in row):
2049 object_records.update_collection_record(
2050 ATTENTION_COUNTS_COLLECTION, source_id, row,
2051 base_dir=base_dir, actor=ATTENTION_ACTOR, preserve_read_only=True)
2052 except Exception as exc: # noqa: BLE001
2053 log(f"Attention: {source_id} count could not be stored: {exc}", "ERROR")
2054
2055 if counted or failed:
2056 log(f"Attention: counted {counted} queue(s)"
2057 + (f", {failed} provider(s) failed" if failed else "")
2058 + (f", {muted} muted" if muted else ""))
2059 summary = {"sources": len(sources), "counted": counted, "failed": failed, "muted": muted}
2060 if skipped_declared:
2061 # Counted per viewer when shown (object_attention), not here.
2062 summary["declared"] = skipped_declared
2063 return summary
2064
2065
2066def _connector_package_roots() -> list[str]:
2067 """Package source roots the reconcile pass loads connectors from, private
2068 overlay first -- mirrors object_server's resolution so a private connector
2069 (e.g. Mailcow, in packages-private/) is found on the deployment where it is
2070 installed, and a private declaration shadows an open one for a collection."""
2071 roots: list[str] = []
2072 packages = os.environ.get("DBBASIC_PACKAGES_DIR", object_packages.PACKAGES_DIR)
2073 # Private overlay defaults to a sibling of the active packages dir (same
2074 # rule as object_server._private_packages_dir), so overriding the packages
2075 # dir isolates the overlay too.
2076 private = os.environ.get("DBBASIC_PRIVATE_PACKAGES_DIR") or str(Path(packages).parent / "packages-private")
2077 if private and Path(private).is_dir():
2078 roots.append(private)
2079 roots.append(packages)
2080 return roots
2081
2082
2083def _connector_declarations() -> list[dict]:
2084 """All connector declarations across roots, deduped by collection with the
2085 private overlay winning (first root wins)."""
2086 decls: list[dict] = []
2087 seen: set[str] = set()
2088 for root in _connector_package_roots():
2089 for decl in object_packages.iter_connectors(root=root):
2090 if decl["collection"] in seen:
2091 continue
2092 seen.add(decl["collection"])
2093 decls.append(decl)
2094 return decls
2095
2096
2097def process_connectors(*, base_dir: Path | str = "data") -> dict | None:
2098 """03 external connectors: reconcile each declared collection against its
2099 outside system.
2100
2101 For every collection a package declares a connector for, selects the rows
2102 whose desired state the external world doesn't match yet (pending /
2103 pending_delete, backoff due), calls the connector's `reconcile(record)`, and
2104 writes the outcome back via object_connectors.plan_sync -- synced/deleted on
2105 success, retry-with-backoff on a transient error, dead on a permanent one or
2106 exhausted attempts. The driver owns the lifecycle; the connector only
2107 reports ok/error/permanent. Per-row try/except isolates one bad row, and
2108 per-collection isolation keeps one bad connector from stopping the rest.
2109
2110 Returns None when disabled or nothing declares a connector; else a summary.
2111 """
2112 if not object_connectors.connectors_pass_enabled(base_dir=base_dir):
2113 return None
2114 decls = _connector_declarations()
2115 if not decls:
2116 return None
2117
2118 config = object_connectors.connector_config_from_env()
2119 now = datetime.now(timezone.utc)
2120 reconciled = synced = dead = skipped = 0
2121
2122 for decl in decls:
2123 try:
2124 records = object_records.read_collection_records(decl["collection"], base_dir=base_dir)
2125 except (object_collections.CollectionNotFoundError,
2126 object_collections.InvalidCollectionNameError, OSError, ValueError):
2127 continue # collection not installed here -> nothing to reconcile
2128 due = [r for r in records if object_connectors.is_due(r, now)]
2129 if not due:
2130 continue
2131 due.sort(key=lambda r: (str(r.get("sync_next_at") or ""), str(r.get("created_at") or "")))
2132 try:
2133 reconcile = object_connectors.load_connector(decl["module"], decl["entry"])
2134 except object_connectors.ConnectorLoadError as exc:
2135 log(f"Connector: {decl['package_id']}/{decl['collection']} not loaded: {exc}", "ERROR")
2136 continue
2137
2138 for record in due[:config.batch_size]:
2139 try:
2140 outcome = reconcile(record, base_dir=base_dir)
2141 if not isinstance(outcome, dict):
2142 outcome = {"ok": False, "error": f"connector returned {type(outcome).__name__}, expected dict"}
2143 except Exception as exc: # noqa: BLE001 -- transient by default; isolate one bad row
2144 outcome = {"ok": False, "error": str(exc)}
2145 if outcome.get("skip"):
2146 # The connector declined this tick (e.g. unconfigured): leave the
2147 # row exactly as-is -- not an attempt, not a failure, so it waits
2148 # inspectably instead of backing off toward `dead`. Mirrors the
2149 # outbox's "unconfigured = queue only" posture.
2150 skipped += 1
2151 continue
2152 update = object_connectors.plan_sync(record, outcome, config, now=now)
2153 try:
2154 object_records.update_collection_record(
2155 decl["collection"], record["id"], update,
2156 base_dir=base_dir, actor=object_connectors.DEFAULT_ACTOR,
2157 preserve_read_only=True,
2158 )
2159 except Exception as exc: # noqa: BLE001
2160 log(f"Connector: {decl['collection']} {record.get('id')} status write failed: {exc}", "ERROR")
2161 continue
2162 reconciled += 1
2163 status = update.get(object_connectors.SYNC_STATUS_FIELD)
2164 if status in (object_connectors.STATUS_SYNCED, object_connectors.STATUS_DELETED):
2165 synced += 1
2166 elif status == object_connectors.STATUS_DEAD:
2167 dead += 1
2168
2169 if reconciled:
2170 log(f"Connectors: reconciled {reconciled} ({synced} synced, {dead} dead)")
2171 return {"reconciled": reconciled, "synced": synced, "dead": dead, "skipped": skipped}
2172
2173
2174# --- Main ---
2175
2176def shutdown(signum, frame):
2177 global _running
2178 log("Shutting down...")
2179 _running = False
2180
2181
2182def main():
2183 import argparse
2184
2185 parser = argparse.ArgumentParser(description="Object Primitive Daemon")
2186 parser.add_argument("--interval", type=float, default=1.0,
2187 help="Poll interval in seconds (default: 1.0)")
2188 args = parser.parse_args()
2189
2190 # The primitive-runtime passes (scheduler/queue/events trigger objects)
2191 # need the optional dbbasic_object_core runtime. The storage passes
2192 # (compaction, auto-transitions, cleanups) are stdlib and must run
2193 # regardless -- a deployment without the runtime still gets them.
2194 try:
2195 from dbbasic_object_core.runtime.object_runtime import ObjectRuntime
2196 except ImportError:
2197 ObjectRuntime = None
2198 # Native fallback: the repo's own runtime serves the scheduler/queue/
2199 # events passes (load_object + state_manager + execute_object are the
2200 # whole surface they use). The legacy dbbasic_object_core runtime keeps
2201 # precedence where it is installed; deployments without it -- the
2202 # droplet -- get working scheduled tasks instead of a silent disable
2203 # (found 2026-07-24: system_invoice_aging/fin_recurring had NO working
2204 # schedule path in production because this import was missing).
2205 if ObjectRuntime is None:
2206 try:
2207 from python_object_runtime import PythonObjectRuntime as _NativeRuntime
2208 except ImportError:
2209 _NativeRuntime = None
2210 else:
2211 _NativeRuntime = None
2212
2213 # Same data-dir resolution as the server: env first, ./data fallback.
2214 base_dir = os.environ.get("DBBASIC_DATA_DIR", "data")
2215
2216 signal.signal(signal.SIGTERM, shutdown)
2217 signal.signal(signal.SIGINT, shutdown)
2218
2219 print("=" * 60)
2220 print("Object Primitive Daemon")
2221 print("=" * 60)
2222 print(f"Poll interval: {args.interval}s")
2223 print(f"Data dir: {base_dir}")
2224 print(f"Object roots: {', '.join(str(root) for root in _object_roots())}")
2225 if ObjectRuntime is None and _NativeRuntime is None:
2226 print("Object runtime: NOT installed (scheduler/queue/events passes disabled)")
2227 else:
2228 _runtime_label = "dbbasic_object_core" if ObjectRuntime is not None else "native (python_object_runtime)"
2229 print(f"Object runtime: {_runtime_label}")
2230 print(f"Scheduler: {'enabled' if _find_trigger_file('scheduler') else 'no scheduler object'}")
2231 print(f"Queue: {'enabled' if _find_trigger_file('queue') else 'no queue object'}")
2232 print(f"Events: {'enabled' if _find_trigger_file('events') else 'no events object'}")
2233 try:
2234 import object_sandbox
2235
2236 print(f"User objects: {object_sandbox._verdict(object_sandbox.isolation_status())}")
2237 except Exception as exc: # noqa: BLE001 -- a banner line never stops the daemon
2238 print(f"User objects: status unavailable ({exc})")
2239 print(f"Croniter: {'available' if croniter else 'NOT installed (cron tasks cannot run; pip install -e .[scheduler])'}")
2240 print(f"Rate limit cleanup: {'enabled' if (Path(base_dir) / 'ratelimit').exists() else 'no ratelimit dir yet'}")
2241 print(f"Compaction interval: {_env_int(COMPACTION_INTERVAL_SECONDS_ENV, _DEFAULT_COMPACTION_INTERVAL_SECONDS)}s")
2242 _startup_rules = auto_transition_rules_from_env()
2243 print(
2244 f"Auto-transition rules: {len(_startup_rules)} configured "
2245 f"(interval {_env_int(AUTO_TRANSITION_INTERVAL_SECONDS_ENV, _DEFAULT_AUTO_TRANSITION_INTERVAL_SECONDS)}s)"
2246 )
2247 print(f"Rollups: {'enabled' if object_rollups.rollup_pass_enabled(base_dir=base_dir) else 'disabled (rollup_enabled flag off)'}")
2248 print(
2249 f"Materialize: {'enabled' if object_materialize.materialize_pass_enabled(base_dir=base_dir) else 'disabled (materialize_enabled flag off)'} "
2250 f"(interval {_env_int(MATERIALIZE_INTERVAL_SECONDS_ENV, _DEFAULT_MATERIALIZE_INTERVAL_SECONDS)}s)"
2251 )
2252 print(f"Notify: {'enabled' if object_notify.notify_pass_enabled(base_dir=base_dir) else 'disabled (notify_enabled flag off)'} (every poll)")
2253 print(f"Change dispatch: {'enabled' if object_change_dispatch.change_dispatch_enabled(base_dir=base_dir) else 'disabled (DBBASIC_ENABLE_CHANGE_DISPATCH unset)'}")
2254 _clp = object_record_changes.retention_policy()
2255 if _clp["days"] or _clp["max_entries"]:
2256 _bounds = " and ".join(
2257 part for part in (
2258 f"{_clp['days']}d" if _clp["days"] else "",
2259 f"{_clp['max_entries']} entries" if _clp["max_entries"] else "",
2260 ) if part)
2261 _fate = "archived" if _clp["archive"] else "DELETED"
2262 _keep = ("all archives kept" if not _clp["keep_archives"]
2263 else f"newest {_clp['keep_archives']} archives kept")
2264 print(f"Change logs: keep {_bounds}; older entries {_fate} ({_keep})")
2265 else:
2266 print("Change logs: unbounded (set DBBASIC_CHANGE_LOG_RETENTION_DAYS "
2267 "or DBBASIC_CHANGE_LOG_MAX_ENTRIES)")
2268 # Books readiness is advisory, never a gate -- the composers are
2269 # deliberately soft dependencies. But a composer that skips because its
2270 # accounts are unmapped otherwise says so only in a return value nobody
2271 # reads, which is harmless on a demo box and a data-integrity hole the
2272 # day real books arrive. Say it out loud at boot instead.
2273 try:
2274 _books = object_books_status.books_status(base_dir=base_dir)
2275 if _books["ready"]:
2276 print("Books: ready (every installed composer can post)")
2277 else:
2278 print(f"Books: NOT READY -- {_books['summary']}")
2279 for _problem in _books.get("problems", [])[:6]:
2280 print(f" - {_problem.get('id')}: {_problem.get('impact')}")
2281 except Exception as _exc: # never let a status check stop the daemon
2282 print(f"Books: status unavailable ({_exc})")
2283 # Same posture for reactions: packages that declare handlers or
2284 # schedules which cannot run here are named at boot, not discovered
2285 # weeks later as invoices that never flipped to paid.
2286 try:
2287 _reactions = object_daemon_status.reactions_status(base_dir=base_dir)
2288 if not _reactions["problems"]:
2289 print("Reactions: every installed handler and schedule can run")
2290 else:
2291 print("Reactions: NOT ALL RUNNING")
2292 for _problem in _reactions["problems"]:
2293 if _problem["id"] == "daemon_not_running":
2294 continue # this process IS the daemon
2295 print(f" - {_problem['id']}: {_problem['impact']} -- {_problem['fix']}")
2296 except Exception as _exc:
2297 print(f"Reactions: status unavailable ({_exc})")
2298 _smtp_config = object_email.smtp_config_from_env()
2299 if not object_email.email_pass_enabled(base_dir=base_dir):
2300 _email_state = "disabled (email_enabled flag off)"
2301 elif not _smtp_config.configured:
2302 _email_state = f"queuing only (DBBASIC_SMTP_MODE={_smtp_config.mode!r}, not configured)"
2303 else:
2304 _email_state = f"enabled (mode={_smtp_config.mode})"
2305 print(f"Email: {_email_state}")
2306 _connector_decls = _connector_declarations()
2307 if not object_connectors.connectors_pass_enabled(base_dir=base_dir):
2308 _connectors_state = "disabled (connectors_enabled flag off)"
2309 elif not _connector_decls:
2310 _connectors_state = "no connectors declared"
2311 else:
2312 _connectors_state = f"{len(_connector_decls)} connector(s): " + ", ".join(
2313 f"{d['package_id']}/{d['collection']}" for d in _connector_decls)
2314 print(f"Connectors: {_connectors_state}")
2315 try:
2316 _attention_sources = object_records.read_collection_records(
2317 ATTENTION_SOURCES_COLLECTION, base_dir=base_dir)
2318 except Exception:
2319 _attention_sources = None
2320 if _attention_sources is None:
2321 _attention_state = "no attention_sources collection (app-nav not installed)"
2322 elif not _attention_sources:
2323 _attention_state = "no queues declared"
2324 else:
2325 _attention_state = (
2326 f"{len(_attention_sources)} queue(s) "
2327 f"(interval {_env_int(ATTENTION_INTERVAL_ENV, _DEFAULT_ATTENTION_INTERVAL)}s)")
2328 print(f"Attention: {_attention_state}")
2329 if object_analytics.analytics_enabled():
2330 print(f"Analytics: capture ON (retention {object_analytics.retention_days()}d)")
2331 else:
2332 print("Analytics: capture off (DBBASIC_ANALYTICS unset)")
2333 # Stated in words, every boot, because the cookie is the only thing
2334 # this server stores on somebody else's device and the setting that
2335 # turns it on is one word in an env file. An operator should not have
2336 # to go and read a document to find out what they took on.
2337 print(f"Analytics: {object_analytics.visitor_cookie_posture()}")
2338 try:
2339 _backups = object_backup_schedule.status(base_dir)
2340 print(f"Backups: {object_backup_schedule.summary_line(_backups)}")
2341 if _backups.get("enabled"):
2342 print(f" destination: {_backups.get('destination')}")
2343 for _warning in _backups.get("warnings") or []:
2344 print(f" - warning: {_warning}")
2345 except Exception as _exc: # a banner line never stops the daemon
2346 print(f"Backups: status unavailable ({_exc})")
2347 print()
2348 print("Press Ctrl+C to stop")
2349 print("=" * 60)
2350 print()
2351
2352 if ObjectRuntime is not None:
2353 runtime = ObjectRuntime(base_dir=str(base_dir))
2354 elif _NativeRuntime is not None:
2355 runtime = _NativeRuntime()
2356 else:
2357 runtime = None
2358 last_event_cleanup = 0.0
2359
2360 while _running:
2361 _beat(base_dir)
2362 if runtime is not None:
2363 try:
2364 process_scheduler(runtime)
2365 except Exception as e:
2366 log(f"Scheduler error: {e}", 'ERROR')
2367
2368 try:
2369 process_queue(runtime)
2370 except Exception as e:
2371 log(f"Queue error: {e}", 'ERROR')
2372
2373 try:
2374 process_events(runtime)
2375 except Exception as e:
2376 log(f"Events error: {e}", 'ERROR')
2377
2378 try:
2379 cleanup_ratelimit(base_dir=base_dir)
2380 except Exception as e:
2381 log(f"Cleanup error: {e}", 'ERROR')
2382
2383 try:
2384 process_compactions(base_dir=base_dir)
2385 except Exception as e:
2386 log(f"Compaction error: {e}", 'ERROR')
2387
2388 try:
2389 process_stale_transitions(base_dir=base_dir)
2390 except Exception as e:
2391 log(f"Auto-transition error: {e}", 'ERROR')
2392
2393 try:
2394 process_rollups(base_dir=base_dir)
2395 except Exception as e:
2396 log(f"Rollup error: {e}", 'ERROR')
2397
2398 try:
2399 process_materializations(base_dir=base_dir)
2400 except Exception as e:
2401 log(f"Materialize error: {e}", 'ERROR')
2402
2403 try:
2404 process_notifications(base_dir=base_dir)
2405 except Exception as e:
2406 log(f"Notify error: {e}", 'ERROR')
2407
2408 try:
2409 object_change_dispatch.dispatch_pending(base_dir=base_dir)
2410 except Exception as e:
2411 log(f"Change dispatch error: {e}", 'ERROR')
2412
2413 try:
2414 process_email_outbox(base_dir=base_dir)
2415 except Exception as e:
2416 log(f"Email error: {e}", 'ERROR')
2417
2418 try:
2419 process_connectors(base_dir=base_dir)
2420 except Exception as e:
2421 log(f"Connectors error: {e}", 'ERROR')
2422
2423 try:
2424 process_analytics_retention(base_dir=base_dir)
2425 except Exception as e:
2426 log(f"Analytics retention error: {e}", 'ERROR')
2427
2428 try:
2429 process_change_log_retention(base_dir=base_dir)
2430 except Exception as e:
2431 log(f"Change log retention error: {e}", 'ERROR')
2432
2433 try:
2434 process_restore_point_retention(base_dir=base_dir)
2435 except Exception as e:
2436 log(f"Restore point retention error: {e}", 'ERROR')
2437
2438 try:
2439 process_scheduled_backup(base_dir=base_dir)
2440 except Exception as e:
2441 log(f"Scheduled backup error: {e}", 'ERROR')
2442
2443 try:
2444 process_attention(base_dir=base_dir)
2445 except Exception as e:
2446 log(f"Attention error: {e}", 'ERROR')
2447
2448 now = time.time()
2449 if now - last_event_cleanup >= EVENT_CLEANUP_INTERVAL_SECONDS:
2450 last_event_cleanup = now
2451 try:
2452 cleanup_events(base_dir=base_dir)
2453 except Exception as e:
2454 log(f"Event cleanup error: {e}", 'ERROR')
2455
2456 # Sleep in small increments for responsive shutdown
2457 deadline = now + args.interval
2458 while _running and time.time() < deadline:
2459 time.sleep(0.1)
2460
2461 log("Daemon stopped.")
2462
2463
2464if __name__ == "__main__":
2465 main()