Database Service
LOG_RECORD_COLUMNS = ('seq', 'timestamp', 'level', 'logger_name', 'func_name', 'lineno', 'message', 'exc_info', 'app_key', 'instance_name', 'instance_index', 'execution_id', 'author')
module-attribute
log_records table columns (excluding the autoincrement id). Public so scripts/seed_db.py
can import the single source of truth instead of hand-keeping a duplicate tuple.
DatabaseService
Bases: DatabaseWriteQueueMixin, DatabaseRetentionMixin, DatabaseSizeFailsafeMixin, Service
Manages the SQLite database for operational telemetry.
Handles PRAGMA user_version migrations, heartbeat updates, the write queue, retention cleanup of old execution records, and the database size failsafe.
Source code in src/hassette/core/database_service.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 | |
shutdown_hook_timeout_applies: bool = False
class-attribute
A foundation service: the root's foundation stage bounds its shutdown, and its drain has a fixed cap.
CONN_ATTRS = ('_read_db', '_db')
class-attribute
instance-attribute
Connection attributes, in the order both teardown paths close them.
Read first so the write connection closes last and performs the WAL checkpoint. Named once so a rename cannot leave one of the two reflection-based loops behind.
shutdown_snapshot_task: asyncio.Task[bool] | None = None
instance-attribute
The shutdown snapshot's copy, once write_shutdown_snapshot() started it; the hard exit waits for it.
config_log_level: LogLevel
property
Log level for this service, read from logging.database_service in the config.
is_db_ready: bool
property
Whether the write database connection is open and usable.
is_accepting_writes: bool
property
Whether the write queue is live and accepting submissions.
False before on_initialize() creates the queue and after shutdown drains it.
db: aiosqlite.Connection
property
Return the active write database connection.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database connection is not initialized. |
read_db: aiosqlite.Connection
property
Return the dedicated read-only database connection.
Uses a separate WAL snapshot so reads never block the write worker.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the read connection is not initialized. |
on_initialize() -> None
async
Set up the database: check schema version, run migrations and open connection.
Source code in src/hassette/core/database_service.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
serve() -> None
async
Run the heartbeat, retention, and size failsafe loop until shutdown.
Source code in src/hassette/core/database_service.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | |
on_shutdown() -> None
async
Drain the write queue, cancel the worker, and close the database connections.
The root writes the shutdown snapshot after the foundation stage (write_shutdown_snapshot()).
Source code in src/hassette/core/database_service.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
write_shutdown_snapshot() -> None
async
Write database.shutdown_snapshot_path, last in shutdown, after the foundation stage.
The root calls it even when the drain, the close or the foundation stage itself failed, so the snapshot then holds every write that committed. It opens its own connection to the database file, so the closed service connections don't affect it. A failure is logged, never raised: shutdown carries on, and the previous snapshot stays in place.
Nothing bounds the copy. It runs in a worker thread inside a shielded task kept on
shutdown_snapshot_task, so if this await is cancelled the copy still finishes and logs its outcome,
and the hard exit waits for it. Only a kill (the supervisor's stop grace period) cuts it short, which
leaves the previous snapshot in place.
Source code in src/hassette/core/database_service.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
close_connections() -> None
async
Close both database connections. Idempotent -- safe to call multiple times.
aiosqlite's worker threads are set to daemon in on_initialize() as a safety net, but this method still does a best-effort close to avoid resource warnings and ensure clean WAL checkpoints.
Propagates the first close failure rather than swallowing it: both call sites feed teardown
accounting that has to tell a clean close from one that left a connection in an unknown
state -- an escaping exception makes the shutdown outcome FAILED, from cleanup() and
on_shutdown() alike. See
close_connection_pair() for the close and cancellation mechanics.
Source code in src/hassette/core/database_service.py
398 399 400 401 402 403 404 405 406 407 408 409 410 411 | |
cleanup() -> None
async
Close database connections if on_shutdown was interrupted or never ran.
Source code in src/hassette/core/database_service.py
413 414 415 416 | |
resolve_db_path() -> Path
Resolve the database path from config or use default.
Source code in src/hassette/core/database_service.py
418 419 420 421 422 | |
get_expected_head_version() -> int
Return the highest migration version number from migrations_sql/ (synchronous).
Scans the migrations_sql/ directory for *.sql files with numeric stems and returns the largest version number found.
Source code in src/hassette/core/database_service.py
424 425 426 427 428 429 430 431 432 433 | |
get_current_db_version(db_path: Path) -> int
Return PRAGMA user_version from the on-disk DB (synchronous). Returns 0 for fresh databases.
Source code in src/hassette/core/database_service.py
435 436 437 | |
handle_schema_version(db_path: Path) -> None
async
Check schema version and handle mismatches.
If the DB file does not exist yet, does nothing (migrations will create it). If the DB version matches the expected head, does nothing. If the DB version is behind head (0 < current < head), does nothing — run_migrations() will apply pending migrations incrementally, preserving data. If the DB version is 0 on an existing file (pre-PRAGMA-era or fresh DB with no migrations applied), deletes the file so migrations recreate it cleanly. If the DB version is ahead of head (newer DB on older binary), logs an ERROR and raises SchemaVersionError — auto-delete is refused in this case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
Path
|
Path to the SQLite database file. |
required |
Raises:
| Type | Description |
|---|---|
SchemaVersionError
|
When the DB version is ahead of the expected head version. |
RuntimeError
|
When the DB file cannot be deleted due to permissions. |
Source code in src/hassette/core/database_service.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | |
run_migrations() -> None
Run PRAGMA user_version migrations to the latest version (synchronous, called via to_thread).
auto_vacuum = INCREMENTAL is set by the runner before any tables are created.
Source code in src/hassette/core/database_service.py
500 501 502 503 504 505 | |
catch_up_cleanup_at_startup() -> None
async
Run the size failsafe, then retention cleanup, once during on_initialize().
Runs directly on the write connection, before the write worker starts.
Source code in src/hassette/core/database_service.py
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | |
set_pragmas() -> None
async
Configure SQLite PRAGMAs for performance and safety.
Source code in src/hassette/core/database_service.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 | |
update_heartbeat() -> None
async
Await a heartbeat update for the current session.
Early-return guards run inline; the DB write is awaited via submit() so that _consecutive_heartbeat_failures is updated before returning.
The submit() call is bounded by _HEARTBEAT_WRITE_TIMEOUT_SECONDS. submit()'s own queue timeout only covers the wait before the write starts; a worker wedged inside a write never raises, so without this outer bound serve() would park on submit() forever and never reach its failure-count escalation. Either timeout surfaces as the same TimeoutError: the queue was backed up past its limit, or the worker is wedged. A timeout, or a WriteQueueUnavailableError from submit(), is a failed attempt identically to a raised sqlite3.Error/OSError/ValueError. A failed attempt counts a strike only when _write_progress_count has not moved since the previous attempt finished (or, on the first attempt, since this one started): a worker still committing writes, such as a long batched retention pass holding the queue, is busy rather than stuck and must not be failed.
This method is the only place _consecutive_heartbeat_failures moves, so one attempt costs at most one strike. Counting the timeout here and the raise inside the queued coroutine would let a single slow-then-failing write consume two of the three, failing the service a full heartbeat interval early.
Source code in src/hassette/core/database_service.py
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 | |
record_heartbeat_failure(message: str, exc: BaseException, progress_baseline: int) -> None
Count a strike for a failed heartbeat attempt unless writes progressed past progress_baseline.
exc is the attempt's failure; its traceback is attached to the logged entry either way.
Source code in src/hassette/core/database_service.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 | |
CleanupAttempt
dataclass
When a maintenance task last tried to enqueue its cleanup, and whether the enqueue went through.
Source code in src/hassette/core/database_service.py
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 | |
next_due(interval: float, *, retry_interval: float) -> float
Return the monotonic time of the next attempt.
A successful enqueue waits the full interval. A dropped one retries after
min(interval, retry_interval): skipping a whole interval would starve the cleanup
under the sustained write-queue backlog it exists to relieve.
Source code in src/hassette/core/database_service.py
669 670 671 672 673 674 675 676 677 | |
maintenance_deadlines(config: DatabaseConfig, last_heartbeat: float, retention_attempt: CleanupAttempt, size_failsafe_attempt: CleanupAttempt) -> tuple[float, float, float]
Return the monotonic (heartbeat, retention, size failsafe) deadlines under config.
A dropped cleanup enqueue retries on the heartbeat cadence (see CleanupAttempt.next_due).
Source code in src/hassette/core/database_service.py
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | |
log_shutdown_snapshot_outcome(service: DatabaseService, snapshot_path: Path, copy: asyncio.Task[bool]) -> None
Log how DatabaseService.write_shutdown_snapshot()'s copy ended.
Source code in src/hassette/core/database_service.py
698 699 700 701 702 703 704 705 706 707 708 709 | |