github_backend
GitHub-based backend for REPLICA mode.
This backend downloads legacy model reference files from GitHub repositories, converts them to the new format, and provides them to REPLICA clients as a fallback when the PRIMARY API is unavailable.
GitHubBackend
Bases: ReplicaBackendBase
Backend that fetches legacy model references from GitHub and converts them.
This backend is designed for REPLICA mode only. It: 1. Downloads legacy JSON files from AI-Horde GitHub repositories 2. Stores them in a local legacy/ folder 3. Converts them to the new format using legacy converters 4. Returns the converted (new format) data 5. Provides a fallback for REPLICA clients when PRIMARY API is down 6. PRIMARYs can initialize for the first time if needed from GitHub
This backend is read-only and enforces REPLICA mode.
Source code in src/horde_model_reference/backends/github_backend.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 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 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
_references_paths_cache
instance-attribute
_invalidation_callbacks
instance-attribute
_category_timestamps
instance-attribute
_last_known_mtimes
instance-attribute
_legacy_json_cache
instance-attribute
_legacy_json_string_cache
instance-attribute
_legacy_cache_timestamps
instance-attribute
_legacy_last_known_mtimes
instance-attribute
_stale_legacy_categories
instance-attribute
cache_ttl_seconds
property
The cache TTL currently enforced for category payloads.
async_lock
property
Asyncio lock usable by subclasses when coordinating coroutines.
__init__
__init__(
*,
base_path: str
| Path = horde_model_reference_paths.base_path,
cache_ttl_seconds: int = horde_model_reference_settings.cache_ttl_seconds,
retry_max_attempts: int = horde_model_reference_settings.legacy_download_retry_max_attempts,
retry_backoff_seconds: float = horde_model_reference_settings.legacy_download_retry_backoff_seconds,
replicate_mode: ReplicateMode = ReplicateMode.REPLICA,
) -> None
Initialize the GitHub backend for REPLICA mode.
Parameters:
-
base_path(str | Path, default:base_path) –Base path for storing model reference files.
-
cache_ttl_seconds(int, default:cache_ttl_seconds) –TTL for internal cache in seconds.
-
retry_max_attempts(int, default:legacy_download_retry_max_attempts) –Max download retry attempts.
-
retry_backoff_seconds(float, default:legacy_download_retry_backoff_seconds) –Backoff time between retries.
-
replicate_mode(ReplicateMode, default:REPLICA) –Must be REPLICA. Defaults to REPLICA.
Raises:
-
ValueError–If replicate_mode is not REPLICA.
Source code in src/horde_model_reference/backends/github_backend.py
_get_file_path_for_validation
Return the converted (v2) file path for mtime validation.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get the file path for.
Returns:
-
Path | None–Path | None: Path to converted file for mtime validation.
Source code in src/horde_model_reference/backends/github_backend.py
_get_legacy_file_path_for_validation
Return the legacy file path for mtime validation.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get the legacy file path for.
Returns:
-
Path | None–Path | None: Path to legacy file for mtime validation.
Source code in src/horde_model_reference/backends/github_backend.py
fetch_category
fetch_category(
category: MODEL_REFERENCE_CATEGORY,
*,
force_refresh: bool = False,
) -> dict[str, Any] | None
Fetch model reference data for a specific category.
Downloads legacy format from GitHub, converts to new format, and returns it.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to fetch.
-
force_refresh(bool, default:False) –If True, force download even if file exists.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
fetch_all_categories
fetch_all_categories(
*, force_refresh: bool = False
) -> dict[MODEL_REFERENCE_CATEGORY, dict[str, Any] | None]
Fetch model reference data for all categories.
Downloads all legacy files from GitHub, converts them, and returns new format data.
Parameters:
-
force_refresh(bool, default:False) –If True, force download all files.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, dict[str, Any] | None]–dict mapping categories to their converted model reference data.
Source code in src/horde_model_reference/backends/github_backend.py
fetch_category_async
async
fetch_category_async(
category: MODEL_REFERENCE_CATEGORY,
*,
httpx_client: AsyncClient | None = None,
force_refresh: bool = False,
) -> dict[str, Any] | None
Asynchronously fetch model reference data for a category.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to fetch.
-
httpx_client(AsyncClient | None, default:None) –Optional httpx async client for downloads.
-
force_refresh(bool, default:False) –If True, force download.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
fetch_all_categories_async
async
fetch_all_categories_async(
*,
httpx_client: AsyncClient | None = None,
force_refresh: bool = False,
) -> dict[MODEL_REFERENCE_CATEGORY, dict[str, Any] | None]
Asynchronously fetch all categories.
Parameters:
-
httpx_client(AsyncClient | None, default:None) –Optional httpx async client.
-
force_refresh(bool, default:False) –If True, force download all.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, dict[str, Any] | None]–dict mapping categories to their data.
Source code in src/horde_model_reference/backends/github_backend.py
needs_refresh
Check if a category needs refresh.
Base class handles all validation including mtime checks via hooks.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to check.
Returns:
-
bool(bool) –True if needs refresh (stale or mtime changed).
Source code in src/horde_model_reference/backends/github_backend.py
mark_stale
Mark a category as stale, requiring refresh.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to mark stale.
Source code in src/horde_model_reference/backends/github_backend.py
get_category_file_path
Get the file path for a category's converted data.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get path for.
Returns:
-
Path | None–Path | None: Path to the converted (new format) file, or None if not available.
Source code in src/horde_model_reference/backends/github_backend.py
get_all_category_file_paths
Get file paths for all categories' converted data.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, Path | None]–dict[MODEL_REFERENCE_CATEGORY, Path | None]: Mapping of categories to their converted file paths.
Source code in src/horde_model_reference/backends/github_backend.py
_load_legacy_json_from_disk
_load_legacy_json_from_disk(
category: MODEL_REFERENCE_CATEGORY, file_path: Path
) -> dict[str, Any] | None
Load legacy data from disk and populate cache via base class.
For text_generation category, loads CSV format (models.csv). For other categories, loads JSON format.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to load.
-
file_path(Path) –Path to the legacy file.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
_read_legacy_csv_to_dict
Read legacy CSV file (models.csv format) and convert to dict format.
Uses the shared csv_rows_to_legacy_dict to replicate convert.py exactly,
including defaults.json merging, instruct_format, correct field ordering,
and backend prefix generation (3 entries per model).
Parameters:
-
file_path(Path) –Path to the legacy CSV file.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
_read_csv_to_dict
Read CSV file and convert to dict format (one entry per base model).
Uses the shared csv_rows_to_legacy_dict without backend prefixes.
Parameters:
-
file_path(Path) –Path to the CSV file.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
_load_converted_from_disk
Load converted (v2 format) data from disk and cache via base class.
All v2 format files (including text_generation.json) are in JSON format. CSV format is only used for legacy files (legacy/models.csv).
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to load.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
get_legacy_json
get_legacy_json(
category: MODEL_REFERENCE_CATEGORY,
redownload: bool = False,
) -> dict[str, Any] | None
Get raw legacy JSON for a specific category without pydantic validation.
This method returns cached legacy format JSON data, downloading if needed. The cache is populated during initialization, downloads, and on-demand loads.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –Category to retrieve.
-
redownload(bool, default:False) –If True, redownload before returning and refresh cache.
Returns:
Source code in src/horde_model_reference/backends/github_backend.py
get_legacy_json_string
get_legacy_json_string(
category: MODEL_REFERENCE_CATEGORY,
redownload: bool = False,
) -> str | None
Get raw legacy JSON string for a specific category without pydantic validation.
This method returns cached legacy format JSON data as a string, downloading if needed. The cache is populated during initialization, downloads, and on-demand loads.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –Category to retrieve.
-
redownload(bool, default:False) –If True, redownload before returning and refresh cache.
Returns:
-
str | None–str | None: The raw legacy JSON string, or None if not found.
Source code in src/horde_model_reference/backends/github_backend.py
_download_and_convert_single
_download_and_convert_single(
category: MODEL_REFERENCE_CATEGORY,
overwrite_existing: bool = False,
) -> None
Download a single legacy file and convert it.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to download and convert.
-
overwrite_existing(bool, default:False) –If True, overwrite existing files.
Source code in src/horde_model_reference/backends/github_backend.py
_download_and_convert_all
Download all legacy files and convert them.
Source code in src/horde_model_reference/backends/github_backend.py
_download_allowed
Return True if downloading is allowed based on replicate mode and settings.
Source code in src/horde_model_reference/backends/github_backend.py
_download_legacy
_download_legacy(
category: MODEL_REFERENCE_CATEGORY,
overwrite_existing: bool = False,
) -> Path | None
Download a single legacy file from GitHub (synchronous).
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to download.
-
overwrite_existing(bool, default:False) –If True, overwrite existing file.
Returns:
-
Path | None–Path | None: Path to the downloaded file, or None on failure.
Source code in src/horde_model_reference/backends/github_backend.py
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 660 661 662 663 664 665 666 667 668 669 670 | |
_download_legacy_async
async
_download_legacy_async(
category: MODEL_REFERENCE_CATEGORY,
httpx_client: AsyncClient | None = None,
overwrite_existing: bool = False,
) -> Path | None
Download a single legacy file from GitHub (asynchronous).
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to download.
-
httpx_client(AsyncClient | None, default:None) –Optional httpx async client for downloads.
-
overwrite_existing(bool, default:False) –If True, overwrite existing file.
Returns:
-
Path | None–Path | None: Path to the downloaded file, or None on failure.
Source code in src/horde_model_reference/backends/github_backend.py
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
register_invalidation_callback
Register a callback to be called when a category is invalidated.
This allows external components (like ModelReferenceManager) to be notified when cached data becomes stale and needs to be refreshed.
Parameters:
-
callback(Callable[[MODEL_REFERENCE_CATEGORY], None]) –Function to call with the invalidated category.
Source code in src/horde_model_reference/backends/base.py
_notify_invalidation
Notify all registered callbacks that a category has been invalidated.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category that was invalidated.
Source code in src/horde_model_reference/backends/base.py
_mark_stale_impl
support_any_writes
Check if this backend supports any write operations (v2 or legacy).
Returns:
-
bool(bool) –True if any write operations are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
supports_writes
Check if this backend supports write operations (v2 format).
Write operations include update_model() and delete_model(). Typically only PRIMARY mode backends support writes.
Returns:
-
bool(bool) –True if write operations are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
supports_legacy_writes
Check if this backend supports write operations in legacy format.
Legacy write operations include update_model_legacy() and delete_model_legacy(). Only available when canonical_format='LEGACY' in PRIMARY mode.
Returns:
-
bool(bool) –True if legacy write operations are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
supports_cache_warming
Check if this backend supports cache warming operations.
Cache warming pre-populates the cache with data to improve initial request performance. Typically only backends with distributed caching (like Redis) support this.
Returns:
-
bool(bool) –True if cache warming is supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
supports_health_checks
Check if this backend supports health check operations.
Health checks verify that the backend's external dependencies (Redis, databases, etc.) are accessible and functioning correctly.
Returns:
-
bool(bool) –True if health checks are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
supports_statistics
Check if this backend supports statistics retrieval.
Statistics provide insights into backend performance, cache hits/misses, etc.
Returns:
-
bool(bool) –True if statistics are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
update_model
update_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_dict: dict[str, Any],
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference.
This is an optional method that write-capable backends can implement. Read-only backends should leave the default implementation which raises NotImplementedError.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_dict(dict[str, Any]) –The model record data as a dictionary.
Parameters:
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support write operations.
Implementation Requirements
- Create model if it doesn't exist
- Update model if it exists
- Ensure atomic writes (use temp files with rename for file-based backends)
- Call mark_stale() after successful write to invalidate cache
- Override supports_writes() to return
True
See Also
- update_model_from_base_model(): Update from pydantic model (automatically provided)
- delete_model(): Delete a model
- supports_writes(): Feature detection method
Source code in src/horde_model_reference/backends/base.py
update_model_from_base_model
update_model_from_base_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_model: BaseModel,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference from a pydantic BaseModel.
This is an optional method that write-capable backends can implement. Read-only backends should leave the default implementation which raises NotImplementedError.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_model(BaseModel) –The model record data as a pydantic BaseModel.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support write operations.
Implementation Note
The base class provides this implementation automatically. It:
1. Checks supports_writes() returns True
2. Converts the pydantic model to dict using model_dump(exclude_unset=True)
3. Calls update_model() with the dictionary
Backends that support writes typically don't need to override this method.
See Also
- update_model(): Update from dictionary (implement this)
- supports_writes(): Feature detection method
Source code in src/horde_model_reference/backends/base.py
delete_model
delete_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Delete a model reference.
This is an optional method that write-capable backends can implement. Read-only backends should leave the default implementation which raises NotImplementedError.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category containing the model.
-
model_name(str) –The name of the model to delete.
Parameters:
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support write operations.
-
KeyError–If the model doesn't exist.
Implementation Requirements
- Raise
KeyErrorif model doesn't exist - Ensure atomic writes
- Call mark_stale() after successful delete to invalidate cache
- Override supports_writes() to return
True
See Also
- update_model(): Update or create a model
- supports_writes(): Feature detection method
Source code in src/horde_model_reference/backends/base.py
update_model_legacy
update_model_legacy(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_dict: dict[str, Any],
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference in legacy format.
This is an optional method that legacy-write-capable backends can implement. Only available when canonical_format='LEGACY' in PRIMARY mode.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_dict(dict[str, Any]) –The model record data in legacy format as a dictionary.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support legacy write operations.
Source code in src/horde_model_reference/backends/base.py
update_model_legacy_from_base_model
update_model_legacy_from_base_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_model: BaseModel,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference in legacy format from a pydantic BaseModel.
This is an optional method that legacy-write-capable backends can implement. Only available when canonical_format='LEGACY' in PRIMARY mode.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_model(BaseModel) –The model record data as a pydantic BaseModel.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support legacy write operations.
Source code in src/horde_model_reference/backends/base.py
delete_model_legacy
delete_model_legacy(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Delete a model reference from legacy format files.
This is an optional method that legacy-write-capable backends can implement. Only available when canonical_format='LEGACY' in PRIMARY mode.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category containing the model.
-
model_name(str) –The name of the model to delete.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support legacy write operations.
Source code in src/horde_model_reference/backends/base.py
warm_cache
Pre-populate cache with all categories for faster initial requests.
This is an optional method that backends with cache warming support can implement. Backends without cache warming should leave the default implementation.
Raises:
-
NotImplementedError–If the backend does not support cache warming.
Source code in src/horde_model_reference/backends/base.py
warm_cache_async
async
Asynchronously pre-populate cache with all categories for faster initial requests.
This is an optional method that backends with cache warming support can implement. Backends without cache warming should leave the default implementation.
Raises:
-
NotImplementedError–If the backend does not support async cache warming.
Source code in src/horde_model_reference/backends/base.py
health_check
Check the health of the backend's external dependencies.
This is an optional method that backends with health check support can implement. Backends without external dependencies should leave the default implementation.
Returns:
-
bool(bool) –True if healthy, False otherwise.
Raises:
-
NotImplementedError–If the backend does not support health checks.
Source code in src/horde_model_reference/backends/base.py
get_statistics
Get backend performance and usage statistics.
This is an optional method that backends with statistics support can implement. The structure of returned statistics is backend-specific.
Returns:
Raises:
-
NotImplementedError–If the backend does not support statistics.
Source code in src/horde_model_reference/backends/base.py
get_replicate_mode
Get the replication mode of this backend.
Returns:
-
ReplicateMode(ReplicateMode) –The replicate mode (PRIMARY or REPLICA).
supports_metadata
Check if this backend supports metadata tracking.
Metadata tracking records operation counts, timestamps, and health metrics for both legacy (v1) and v2 format operations. Typically only PRIMARY mode backends support metadata tracking.
Returns:
-
bool(bool) –True if metadata tracking is supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
get_legacy_metadata
Get legacy format metadata for a specific category.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata(CategoryMetadata) –The legacy metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_legacy_metadata_async
async
Asynchronously get legacy format metadata for a specific category.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata(CategoryMetadata) –The legacy metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_metadata
Get v2 format metadata for a specific category.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata(CategoryMetadata) –The v2 metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_metadata_async
async
Asynchronously get v2 format metadata for a specific category.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata(CategoryMetadata) –The v2 metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_all_legacy_metadata
Get legacy format metadata for all categories.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their legacy metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_all_legacy_metadata_async
async
Asynchronously get legacy format metadata for all categories.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their legacy metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_all_metadata
Get v2 format metadata for all categories.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their v2 metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
get_all_metadata_async
async
Asynchronously get v2 format metadata for all categories.
This is an optional method that metadata-capable backends can implement. Backends without metadata support should leave the default implementation.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their v2 metadata.
Raises:
-
NotImplementedError–If the backend does not support metadata.
Source code in src/horde_model_reference/backends/base.py
_mark_category_fresh
Record that we hold a fresh cache entry for category.
Also updates mtime if a file path is provided by the subclass.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to mark as fresh.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_invalidate_category_timestamp
Drop timestamp knowledge for category without adjusting payloads.
has_cached_data
Check if any data has been cached for this category.
This is a simple existence check that doesn't validate freshness. Use this for initial fetch detection: "Have we loaded this at least once?"
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to check.
Returns:
-
bool(bool) –True if data exists in cache (may be stale), False if never loaded.
Source code in src/horde_model_reference/backends/replica_backend_base.py
is_cache_valid
Check if cached data exists and is still valid for the given category.
This method performs comprehensive validation to determine if cached data can be used without refetching. It's primarily used internally by cache retrieval methods but can also be called directly for validation checks.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to validate.
Returns:
-
bool–True if cache exists and all validation checks pass, False otherwise.
Validation Steps
The method performs checks in the following order:
- Explicit Staleness: Returns False if category is in
_stale_categories - Cache Existence: Returns False if category has never been cached
- Timestamp Existence: Returns False if no timestamp recorded
- TTL Expiration: Checks if
cache_ttl_secondsexceeded (callsmark_stale()if expired) - File Modification: Compares current file mtime with cached mtime (calls
mark_stale()if changed) - Custom Validation: Calls
_additional_cache_validation()for subclass-specific checks
Side Effects
When staleness is detected (TTL expiration or mtime change), this method calls
mark_stale() to trigger invalidation callbacks and notify the manager.
Return Value Semantics
- Returns
Falsefor both "no data" and "stale data" cases - Use
has_cached_data()to distinguish between these cases - Use
needs_refresh()to check staleness without considering initial fetch
Note
This method is thread-safe and uses the internal _lock for synchronization.
Source code in src/horde_model_reference/backends/replica_backend_base.py
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 | |
should_fetch_data
Determine if data should be fetched (initial load OR refresh).
This is a convenience method that combines both initial fetch detection and refresh detection into a single check. Use this when you want to know "should I fetch data now?" regardless of whether it's an initial load or a refresh.
This is equivalent to: not is_cache_valid(category) or needs_refresh(category)
but handles the logic more efficiently.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to check.
Returns:
-
bool(bool) –True if data should be fetched (either initial or refresh), False if cached data is valid and fresh.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_set_cache_ttl_seconds
Allow subclasses to tweak TTL after initialization if desired.
_additional_cache_validation
Perform additional cache validation.
Subclasses can override this to add custom validation logic beyond
TTL and mtime checks. This is called during is_cache_valid().
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to validate.
Returns:
-
bool(bool) –True if cache is valid, False to invalidate.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_fetch_with_cache
_fetch_with_cache(
category: MODEL_REFERENCE_CATEGORY,
fetch_fn: Callable[[], dict[str, Any] | None],
*,
force_refresh: bool = False,
) -> dict[str, Any] | None
Implement standard fetch pattern with automatic caching.
This helper method implements the recommended fetch pattern: 1. Check cache if not forcing refresh 2. Return cached data if valid 3. Fetch data using provided function 4. Store in cache and return
Use this in your fetch_category() implementations to avoid boilerplate.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to fetch.
-
fetch_fn(Callable[[], dict[str, Any] | None]) –Callable that fetches the data (no args, returns dict or None).
-
force_refresh(bool, default:False) –If True, skip cache check and force fetch.
Returns:
Example
def fetch_category(self, category, *, force_refresh=False): return self._fetch_with_cache( category, lambda: self._fetch_from_source(category), force_refresh=force_refresh )
Source code in src/horde_model_reference/backends/replica_backend_base.py
_get_from_cache
Get data from cache if valid.
This is the primary method subclasses should use to retrieve cached data. It handles all validation logic internally, including initial fetch detection (returns None if data has never been loaded).
This method determines if an INITIAL fetch is needed by checking cache existence.
Use needs_refresh() to check if existing cached data should be RE-fetched.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to retrieve from cache.
Returns:
-
dict[str, Any] | None–dict[str, Any] | None: Cached data if valid, None if cache miss (initial fetch needed) or cache invalid (refresh needed).
Source code in src/horde_model_reference/backends/replica_backend_base.py
_store_in_cache
Store data in cache and mark category as fresh.
This is the primary method subclasses should use to store fetched data. It handles timestamp updates and mtime tracking internally.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to store.
-
data(dict[str, Any] | None) –The data to cache, or None if category has no data.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_invalidate_cache
Invalidate cache for a category without deleting the data.
This marks the category as stale, forcing a refetch on next access.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to invalidate.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_mark_legacy_category_fresh
Record that we hold a fresh legacy cache entry for category.
Also updates legacy file mtime if a path is provided by the subclass.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to mark as fresh.
Source code in src/horde_model_reference/backends/replica_backend_base.py
is_legacy_cache_valid
Return True if the legacy cache for category is considered fresh.
Performs validation checks for legacy format cache: 1. Staleness check (explicit invalidation) 2. Cache existence check (dict or string) 3. TTL expiration check 4. File mtime check (if legacy file path provided by subclass)
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to validate.
Returns:
-
bool(bool) –True if legacy cache is valid and can be used.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_get_legacy_from_cache
_get_legacy_from_cache(
category: MODEL_REFERENCE_CATEGORY,
) -> tuple[dict[str, Any] | None, str | None]
Get legacy data from cache if valid.
Returns both dict and string representations of legacy JSON.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to retrieve from cache.
Returns:
-
tuple[dict[str, Any] | None, str | None]–tuple[dict | None, str | None]: (legacy_dict, legacy_string) or (None, None) if cache miss.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_store_legacy_in_cache
_store_legacy_in_cache(
category: MODEL_REFERENCE_CATEGORY,
legacy_dict: dict[str, Any] | None,
legacy_string: str | None,
) -> None
Store legacy data in cache and mark category as fresh.
Stores both dict and string representations of legacy JSON.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to store.
-
legacy_dict(dict[str, Any] | None) –The legacy JSON as a dict, or None.
-
legacy_string(str | None) –The legacy JSON as a string, or None.
Source code in src/horde_model_reference/backends/replica_backend_base.py
_invalidate_legacy_cache
Invalidate legacy cache for a category without deleting the data.
This marks the category as stale, forcing a refetch on next access.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to invalidate.