superlocalmemory 3.8.3 → 3.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/README.md +3 -2
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/CLAUDE.md +3 -3
- package/plugin/agents/slm-governance-advisor.md +1 -1
- package/plugin/agents/slm-loop-runner.md +1 -1
- package/plugin/agents/slm-memory-advisor.md +1 -1
- package/plugin/agents/slm-optimize-advisor.md +1 -1
- package/plugin/requirements.txt +1 -1
- package/plugin/skills/slm-cache/SKILL.md +1 -1
- package/plugin/skills/slm-compress/SKILL.md +1 -1
- package/plugin/skills/slm-governance/SKILL.md +1 -1
- package/plugin/skills/slm-graph/SKILL.md +1 -1
- package/plugin/skills/slm-loop/SKILL.md +1 -1
- package/plugin/skills/slm-mesh/SKILL.md +1 -1
- package/plugin/skills/slm-profile/SKILL.md +1 -1
- package/plugin/skills/slm-recall/SKILL.md +1 -1
- package/plugin/skills/slm-remember/SKILL.md +1 -1
- package/plugin/skills/slm-scope/SKILL.md +1 -1
- package/plugin/skills/slm-session/SKILL.md +1 -1
- package/plugin/skills/slm-status/SKILL.md +1 -1
- package/plugin-src/rules/AGENTS.md +1 -1
- package/plugin-src/skills/slm-cache/SKILL.md +1 -1
- package/plugin-src/skills/slm-compress/SKILL.md +1 -1
- package/plugin-src/skills/slm-graph/SKILL.md +1 -1
- package/plugin-src/skills/slm-recall/SKILL.md +1 -1
- package/plugin-src/skills/slm-remember/SKILL.md +1 -1
- package/plugin-src/skills/slm-session/SKILL.md +1 -1
- package/plugin-src/skills/slm-status/SKILL.md +1 -1
- package/pyproject.toml +9 -4
- package/src/superlocalmemory/__init__.py +1 -1
- package/src/superlocalmemory/access/rbac.py +68 -76
- package/src/superlocalmemory/cli/commands.py +158 -404
- package/src/superlocalmemory/cli/ingest_cmd.py +11 -1
- package/src/superlocalmemory/cli/main.py +30 -0
- package/src/superlocalmemory/cli/pending_store.py +39 -14
- package/src/superlocalmemory/core/backend_orchestrator.py +93 -0
- package/src/superlocalmemory/core/component_registry.py +4 -2
- package/src/superlocalmemory/core/config.py +78 -0
- package/src/superlocalmemory/core/consolidation_engine.py +79 -73
- package/src/superlocalmemory/core/embeddings.py +33 -6
- package/src/superlocalmemory/core/engine.py +186 -60
- package/src/superlocalmemory/core/engine_ingestion.py +150 -63
- package/src/superlocalmemory/core/fact_consolidator.py +148 -30
- package/src/superlocalmemory/core/graph_pruner.py +436 -39
- package/src/superlocalmemory/core/ingestion_command.py +273 -32
- package/src/superlocalmemory/core/maintenance_scheduler.py +61 -1
- package/src/superlocalmemory/core/mutations.py +32 -10
- package/src/superlocalmemory/core/recall_pipeline.py +111 -74
- package/src/superlocalmemory/core/registry.py +5 -1
- package/src/superlocalmemory/core/remember_admission.py +152 -0
- package/src/superlocalmemory/core/remember_runtime.py +712 -0
- package/src/superlocalmemory/core/remote_mode.py +3 -1
- package/src/superlocalmemory/core/scale_engine.py +41 -18
- package/src/superlocalmemory/core/store_pipeline.py +18 -4
- package/src/superlocalmemory/encoding/entity_resolver.py +18 -11
- package/src/superlocalmemory/graph/cozo_backend.py +5 -5
- package/src/superlocalmemory/hooks/_outcome_common.py +9 -2
- package/src/superlocalmemory/hooks/adapter_base.py +58 -44
- package/src/superlocalmemory/hooks/ide_connector.py +26 -8
- package/src/superlocalmemory/hooks/portable_kit.py +105 -9
- package/src/superlocalmemory/hooks/prewarm_auth.py +21 -2
- package/src/superlocalmemory/infra/auth_middleware.py +3 -1
- package/src/superlocalmemory/infra/cloud_backup.py +26 -27
- package/src/superlocalmemory/infra/event_bus.py +250 -88
- package/src/superlocalmemory/learning/bandit.py +50 -1
- package/src/superlocalmemory/learning/consolidation_cycle.py +33 -16
- package/src/superlocalmemory/learning/entity_compiler.py +148 -132
- package/src/superlocalmemory/learning/memory_merge.py +97 -82
- package/src/superlocalmemory/learning/reward_archive.py +98 -90
- package/src/superlocalmemory/learning/reward_boost.py +40 -30
- package/src/superlocalmemory/learning/source_quality.py +38 -35
- package/src/superlocalmemory/mcp/_daemon_proxy.py +38 -15
- package/src/superlocalmemory/mcp/http_transport.py +335 -3
- package/src/superlocalmemory/mcp/tools_active.py +4 -41
- package/src/superlocalmemory/mcp/tools_core.py +26 -87
- package/src/superlocalmemory/mcp/tools_evolution.py +5 -10
- package/src/superlocalmemory/optimize/proxy/capture.py +196 -8
- package/src/superlocalmemory/retrieval/engine.py +15 -4
- package/src/superlocalmemory/retrieval/entity_channel.py +25 -1
- package/src/superlocalmemory/retrieval/reranker.py +130 -22
- package/src/superlocalmemory/retrieval/spreading_activation.py +20 -12
- package/src/superlocalmemory/retrieval/vector_store.py +84 -69
- package/src/superlocalmemory/server/loopback.py +85 -0
- package/src/superlocalmemory/server/origin.py +9 -4
- package/src/superlocalmemory/server/profile_runtime.py +14 -0
- package/src/superlocalmemory/server/routes/abstraction.py +2 -4
- package/src/superlocalmemory/server/routes/agents.py +3 -5
- package/src/superlocalmemory/server/routes/backup.py +6 -2
- package/src/superlocalmemory/server/routes/behavioral.py +11 -25
- package/src/superlocalmemory/server/routes/brain.py +6 -9
- package/src/superlocalmemory/server/routes/compliance.py +20 -23
- package/src/superlocalmemory/server/routes/config_api.py +83 -0
- package/src/superlocalmemory/server/routes/entity.py +3 -7
- package/src/superlocalmemory/server/routes/evolution.py +3 -5
- package/src/superlocalmemory/server/routes/helpers.py +57 -25
- package/src/superlocalmemory/server/routes/insights.py +2 -4
- package/src/superlocalmemory/server/routes/learning.py +2 -5
- package/src/superlocalmemory/server/routes/lifecycle.py +2 -4
- package/src/superlocalmemory/server/routes/memories.py +119 -98
- package/src/superlocalmemory/server/routes/mesh.py +7 -2
- package/src/superlocalmemory/server/routes/profiles.py +20 -21
- package/src/superlocalmemory/server/routes/rbac.py +0 -1
- package/src/superlocalmemory/server/routes/tiers.py +28 -35
- package/src/superlocalmemory/server/routes/timeline.py +2 -4
- package/src/superlocalmemory/server/routes/v3_api.py +85 -93
- package/src/superlocalmemory/server/unified_daemon.py +400 -140
- package/src/superlocalmemory/server/write_identity.py +22 -4
- package/src/superlocalmemory/storage/admission_codec.py +119 -0
- package/src/superlocalmemory/storage/admission_journal.py +728 -0
- package/src/superlocalmemory/storage/database.py +168 -19
- package/src/superlocalmemory/storage/deferred_writes.py +209 -0
- package/src/superlocalmemory/storage/embedding_migrator.py +19 -0
- package/src/superlocalmemory/storage/memory_write.py +115 -0
- package/src/superlocalmemory/storage/migration_runner.py +44 -0
- package/src/superlocalmemory/storage/migrations/M028_fact_entity_associations.py +113 -78
- package/src/superlocalmemory/storage/migrations/M031_dead_letter_operations.py +80 -0
- package/src/superlocalmemory/storage/migrations/M032_write_coordinator_admission.py +188 -0
- package/src/superlocalmemory/storage/read_connection.py +115 -0
- package/src/superlocalmemory/storage/write_coordinator.py +756 -0
- package/src/superlocalmemory/storage/write_lock.py +88 -0
- package/src/superlocalmemory/ui/index.html +1 -1
- package/src/superlocalmemory/ui/js/auto-settings.js +14 -1
- package/src/superlocalmemory/ui/js/od-settings.js +9 -3
|
@@ -13,6 +13,7 @@ from __future__ import annotations
|
|
|
13
13
|
|
|
14
14
|
import hashlib
|
|
15
15
|
import json
|
|
16
|
+
import logging
|
|
16
17
|
import sqlite3
|
|
17
18
|
import threading
|
|
18
19
|
import time
|
|
@@ -21,14 +22,13 @@ from dataclasses import dataclass, field
|
|
|
21
22
|
from enum import Enum
|
|
22
23
|
from typing import Any, Callable
|
|
23
24
|
|
|
24
|
-
import logging
|
|
25
|
-
|
|
26
25
|
from superlocalmemory.storage.database import DatabaseManager
|
|
27
26
|
|
|
28
27
|
logger = logging.getLogger("superlocalmemory.ingestion_command")
|
|
29
28
|
|
|
30
29
|
_MATERIALIZATION_LOCKS = tuple(threading.RLock() for _ in range(64))
|
|
31
30
|
_MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS = 10
|
|
31
|
+
_NEVER_RETRY_AT = 9_999_999_999.0
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
def _materialization_lock(operation_id: str) -> threading.RLock:
|
|
@@ -48,6 +48,10 @@ class IdempotencyConflict(ValueError):
|
|
|
48
48
|
"""The same idempotency key was reused for different immutable evidence."""
|
|
49
49
|
|
|
50
50
|
|
|
51
|
+
class IngestionRejectedError(RuntimeError):
|
|
52
|
+
"""Deterministic evidence policy produced no queryable projection."""
|
|
53
|
+
|
|
54
|
+
|
|
51
55
|
class InvalidStateTransition(RuntimeError):
|
|
52
56
|
"""An ingestion operation attempted an illegal or stale transition."""
|
|
53
57
|
|
|
@@ -463,41 +467,245 @@ class IngestionOperationRepository:
|
|
|
463
467
|
derivation_state: dict[str, bool] | None = None,
|
|
464
468
|
last_error: str = "",
|
|
465
469
|
) -> IngestionOperation:
|
|
466
|
-
"""Finish only work owned by the caller's durable lease.
|
|
470
|
+
"""Finish only work owned by the caller's durable lease.
|
|
471
|
+
|
|
472
|
+
Fix E: when transitioning to FAILED and the operation has exhausted
|
|
473
|
+
``_MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS``, atomically INSERT a row
|
|
474
|
+
into ``dead_letter_operations`` and set ``next_retry_at=0`` (no further
|
|
475
|
+
retries scheduled). The original row in ``ingestion_operations`` is
|
|
476
|
+
retained — the dead-letter row is a supplemental audit record, not a
|
|
477
|
+
replacement. Both writes happen inside a single ``db.transaction()``.
|
|
478
|
+
|
|
479
|
+
NOTE (Flaw 1 from CRIT): M031 may not exist if the live database has
|
|
480
|
+
not run migration_runner against it yet. The INSERT is therefore
|
|
481
|
+
wrapped in a try/except so that an absent table degrades gracefully to
|
|
482
|
+
the pre-3.8.4 silent-FAILED behaviour rather than breaking ingestion.
|
|
483
|
+
Operators who have run ``slm migrate`` will get the DLQ row.
|
|
484
|
+
"""
|
|
467
485
|
if target not in {IngestionState.COMPLETE, IngestionState.FAILED}:
|
|
468
486
|
raise InvalidStateTransition(f"enriching -> {target.value}")
|
|
469
487
|
current = self.get(operation_id)
|
|
470
|
-
|
|
471
|
-
|
|
488
|
+
# claim_enriching() already increments attempt_count before the
|
|
489
|
+
# materializer runs. finish_enriching() records that claimed attempt;
|
|
490
|
+
# incrementing again here would dead-letter after only nine real tries
|
|
491
|
+
# while claiming that ten had run.
|
|
492
|
+
attempt_count = current.attempt_count
|
|
493
|
+
is_exhausted = (
|
|
494
|
+
target is IngestionState.FAILED
|
|
495
|
+
and attempt_count >= _MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS
|
|
496
|
+
)
|
|
497
|
+
# Fix E: exhausted → far-future retry_at so list_materializable's
|
|
498
|
+
# `next_retry_at <= now` clause never matches, excluding the
|
|
499
|
+
# dead-lettered op from the work queue permanently.
|
|
500
|
+
# 9_999_999_999 ≈ year 2286 — well beyond any reasonable operation window.
|
|
501
|
+
_NEVER_RETRY: float = 9_999_999_999.0
|
|
502
|
+
retry_at: float = _NEVER_RETRY if is_exhausted else 0.0
|
|
503
|
+
if target is IngestionState.FAILED and not is_exhausted:
|
|
472
504
|
delay = min(2 ** min(max(current.attempt_count, 1), 10), 300)
|
|
473
505
|
retry_at = time.time() + delay
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
506
|
+
|
|
507
|
+
try:
|
|
508
|
+
with self.db.transaction():
|
|
509
|
+
rows = self.db.execute(
|
|
510
|
+
"UPDATE ingestion_operations SET state=?, "
|
|
511
|
+
"final_fact_ids_json=COALESCE(?, final_fact_ids_json), "
|
|
512
|
+
"derivation_version=COALESCE(?, derivation_version), "
|
|
513
|
+
"derivation_state_json=COALESCE(?, derivation_state_json), "
|
|
514
|
+
"lease_owner='', lease_expires_at=0, next_retry_at=?, last_error=?, "
|
|
515
|
+
"updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now') "
|
|
516
|
+
"WHERE operation_id=? AND state='enriching' AND lease_owner=? "
|
|
517
|
+
"RETURNING *",
|
|
518
|
+
(
|
|
519
|
+
target.value,
|
|
520
|
+
_canonical_json(list(final_fact_ids))
|
|
521
|
+
if final_fact_ids is not None
|
|
522
|
+
else None,
|
|
523
|
+
derivation_version,
|
|
524
|
+
_canonical_json(derivation_state)
|
|
525
|
+
if derivation_state is not None
|
|
526
|
+
else None,
|
|
527
|
+
retry_at,
|
|
528
|
+
last_error,
|
|
529
|
+
operation_id,
|
|
530
|
+
owner,
|
|
531
|
+
),
|
|
532
|
+
)
|
|
533
|
+
if not rows:
|
|
534
|
+
raise InvalidStateTransition(
|
|
535
|
+
"enriching lease ownership was lost"
|
|
536
|
+
)
|
|
537
|
+
if is_exhausted:
|
|
538
|
+
# Fix E: INSERT dead-letter row inside the same transaction.
|
|
539
|
+
# Failure to write (e.g. M031 not yet migrated) must NOT
|
|
540
|
+
# abort the state-machine UPDATE — catch at the outer level.
|
|
541
|
+
self.db.execute(
|
|
542
|
+
"INSERT INTO dead_letter_operations "
|
|
543
|
+
"(original_op_id, operation_type, content, "
|
|
544
|
+
" metadata_json, error, attempt_count, "
|
|
545
|
+
" first_attempt_at, dead_lettered_at, profile_id) "
|
|
546
|
+
"VALUES (?, 'M018', ?, ?, ?, ?, "
|
|
547
|
+
" (SELECT CAST(strftime('%s', created_at) AS REAL) "
|
|
548
|
+
" FROM ingestion_operations WHERE operation_id=?), ?, ?)",
|
|
549
|
+
(
|
|
550
|
+
operation_id,
|
|
551
|
+
current.raw_content,
|
|
552
|
+
json.dumps(current.metadata, separators=(",", ":"))
|
|
553
|
+
if current.metadata else None,
|
|
554
|
+
last_error or current.last_error,
|
|
555
|
+
attempt_count,
|
|
556
|
+
operation_id,
|
|
557
|
+
time.time(),
|
|
558
|
+
current.profile_id,
|
|
559
|
+
),
|
|
560
|
+
)
|
|
561
|
+
logger.warning(
|
|
562
|
+
"Operation %s exhausted %d attempts — moved to dead-letter. "
|
|
563
|
+
"Last error: %s",
|
|
564
|
+
operation_id,
|
|
565
|
+
attempt_count,
|
|
566
|
+
last_error or current.last_error,
|
|
567
|
+
)
|
|
568
|
+
except InvalidStateTransition:
|
|
569
|
+
raise
|
|
570
|
+
except Exception as exc:
|
|
571
|
+
# Fix E graceful-degrade: if dead-letter INSERT fails (M031 absent),
|
|
572
|
+
# fall back to the pre-3.8.4 silent-FAILED state so ingestion
|
|
573
|
+
# continues unblocked.
|
|
574
|
+
logger.error(
|
|
575
|
+
"finish_enriching failed (dead-letter path): %s — retrying "
|
|
576
|
+
"without dead-letter INSERT",
|
|
577
|
+
exc,
|
|
578
|
+
)
|
|
579
|
+
rows = self.db.execute(
|
|
580
|
+
"UPDATE ingestion_operations SET state=?, "
|
|
581
|
+
"final_fact_ids_json=COALESCE(?, final_fact_ids_json), "
|
|
582
|
+
"derivation_version=COALESCE(?, derivation_version), "
|
|
583
|
+
"derivation_state_json=COALESCE(?, derivation_state_json), "
|
|
584
|
+
"lease_owner='', lease_expires_at=0, next_retry_at=?, last_error=?, "
|
|
585
|
+
"updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now') "
|
|
586
|
+
"WHERE operation_id=? AND state='enriching' AND lease_owner=? "
|
|
587
|
+
"RETURNING *",
|
|
588
|
+
(
|
|
589
|
+
target.value,
|
|
590
|
+
_canonical_json(list(final_fact_ids))
|
|
591
|
+
if final_fact_ids is not None
|
|
592
|
+
else None,
|
|
593
|
+
derivation_version,
|
|
594
|
+
_canonical_json(derivation_state)
|
|
595
|
+
if derivation_state is not None
|
|
596
|
+
else None,
|
|
597
|
+
retry_at,
|
|
598
|
+
last_error,
|
|
599
|
+
operation_id,
|
|
600
|
+
owner,
|
|
601
|
+
),
|
|
602
|
+
)
|
|
603
|
+
if not rows:
|
|
604
|
+
raise InvalidStateTransition(
|
|
605
|
+
"enriching lease ownership was lost"
|
|
606
|
+
) from exc
|
|
607
|
+
return self._from_row(rows[0])
|
|
608
|
+
|
|
609
|
+
def reap_stuck_enriching(
|
|
610
|
+
self,
|
|
611
|
+
*,
|
|
612
|
+
now: float | None = None,
|
|
613
|
+
limit: int = 100,
|
|
614
|
+
) -> list[str]:
|
|
615
|
+
"""Terminalize expired enrichment leases that exhausted automatic retries.
|
|
616
|
+
|
|
617
|
+
``list_materializable`` intentionally excludes operations at the retry
|
|
618
|
+
cap. If a worker dies while such an operation is still ``enriching``,
|
|
619
|
+
it otherwise becomes a permanent phantom: no worker can reclaim it and
|
|
620
|
+
it never reaches a terminal state. Queryable facts are already durable,
|
|
621
|
+
so reaping abandons only optional derivation work.
|
|
622
|
+
|
|
623
|
+
Each candidate is transitioned with a compare-and-swap update in its
|
|
624
|
+
own bounded transaction. A dead-letter record is supplemental; an
|
|
625
|
+
older database without M031 is still terminalized safely.
|
|
626
|
+
"""
|
|
627
|
+
cutoff = time.time() if now is None else float(now)
|
|
628
|
+
batch_limit = max(1, min(int(limit), 500))
|
|
629
|
+
candidates = self.db.execute(
|
|
630
|
+
"SELECT operation_id, attempt_count, last_error, raw_content, "
|
|
631
|
+
"raw_metadata_json, profile_id FROM ingestion_operations "
|
|
632
|
+
"WHERE state='enriching' AND lease_expires_at <= ? "
|
|
633
|
+
"AND attempt_count >= ? ORDER BY updated_at, operation_id LIMIT ?",
|
|
483
634
|
(
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
else None,
|
|
488
|
-
derivation_version,
|
|
489
|
-
_canonical_json(derivation_state)
|
|
490
|
-
if derivation_state is not None
|
|
491
|
-
else None,
|
|
492
|
-
retry_at,
|
|
493
|
-
last_error,
|
|
494
|
-
operation_id,
|
|
495
|
-
owner,
|
|
635
|
+
cutoff,
|
|
636
|
+
_MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS,
|
|
637
|
+
batch_limit,
|
|
496
638
|
),
|
|
497
639
|
)
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
640
|
+
reaped: list[str] = []
|
|
641
|
+
for row in candidates:
|
|
642
|
+
data = dict(row)
|
|
643
|
+
operation_id = str(data["operation_id"])
|
|
644
|
+
terminal_error = (
|
|
645
|
+
data["last_error"]
|
|
646
|
+
or "reaped: enrichment exhausted automatic attempts"
|
|
647
|
+
)
|
|
648
|
+
try:
|
|
649
|
+
with self.db.transaction():
|
|
650
|
+
updated = self.db.execute(
|
|
651
|
+
"UPDATE ingestion_operations SET state='failed', "
|
|
652
|
+
"lease_owner='', lease_expires_at=0, next_retry_at=?, "
|
|
653
|
+
"last_error=?, "
|
|
654
|
+
"updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now') "
|
|
655
|
+
"WHERE operation_id=? AND state='enriching' "
|
|
656
|
+
"AND lease_expires_at <= ? AND attempt_count >= ? "
|
|
657
|
+
"RETURNING operation_id",
|
|
658
|
+
(
|
|
659
|
+
_NEVER_RETRY_AT,
|
|
660
|
+
terminal_error,
|
|
661
|
+
operation_id,
|
|
662
|
+
cutoff,
|
|
663
|
+
_MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS,
|
|
664
|
+
),
|
|
665
|
+
)
|
|
666
|
+
if not updated:
|
|
667
|
+
continue
|
|
668
|
+
try:
|
|
669
|
+
self.db.execute(
|
|
670
|
+
"INSERT INTO dead_letter_operations "
|
|
671
|
+
"(original_op_id, operation_type, content, "
|
|
672
|
+
"metadata_json, error, attempt_count, "
|
|
673
|
+
"first_attempt_at, dead_lettered_at, profile_id) "
|
|
674
|
+
"VALUES (?, 'M018', ?, ?, ?, ?, "
|
|
675
|
+
"(SELECT CAST(strftime('%s', created_at) AS REAL) "
|
|
676
|
+
"FROM ingestion_operations WHERE operation_id=?), ?, ?)",
|
|
677
|
+
(
|
|
678
|
+
operation_id,
|
|
679
|
+
data["raw_content"],
|
|
680
|
+
data["raw_metadata_json"] or None,
|
|
681
|
+
terminal_error,
|
|
682
|
+
int(data["attempt_count"]),
|
|
683
|
+
operation_id,
|
|
684
|
+
time.time(),
|
|
685
|
+
data["profile_id"],
|
|
686
|
+
),
|
|
687
|
+
)
|
|
688
|
+
except sqlite3.OperationalError as exc:
|
|
689
|
+
if "no such table" not in str(exc).lower():
|
|
690
|
+
raise
|
|
691
|
+
logger.info(
|
|
692
|
+
"Dead-letter table unavailable while reaping %s; "
|
|
693
|
+
"terminal transition preserved",
|
|
694
|
+
operation_id,
|
|
695
|
+
)
|
|
696
|
+
except Exception:
|
|
697
|
+
logger.exception(
|
|
698
|
+
"Failed to reap exhausted ingestion operation %s",
|
|
699
|
+
operation_id,
|
|
700
|
+
)
|
|
701
|
+
continue
|
|
702
|
+
reaped.append(operation_id)
|
|
703
|
+
logger.warning(
|
|
704
|
+
"Reaped exhausted ingestion operation %s at attempt %d",
|
|
705
|
+
operation_id,
|
|
706
|
+
int(data["attempt_count"]),
|
|
707
|
+
)
|
|
708
|
+
return reaped
|
|
501
709
|
|
|
502
710
|
|
|
503
711
|
@dataclass(frozen=True, slots=True)
|
|
@@ -510,6 +718,7 @@ class MaterializationResult:
|
|
|
510
718
|
|
|
511
719
|
|
|
512
720
|
QueryableWriter = Callable[[IngestionRequest, str], list[str]]
|
|
721
|
+
AdmissionValidator = Callable[[IngestionRequest], None]
|
|
513
722
|
Materializer = Callable[
|
|
514
723
|
[IngestionOperation],
|
|
515
724
|
list[str] | tuple[str, ...] | MaterializationResult,
|
|
@@ -526,6 +735,7 @@ class IngestionCommand:
|
|
|
526
735
|
*,
|
|
527
736
|
write_queryable: QueryableWriter,
|
|
528
737
|
materialize: Materializer,
|
|
738
|
+
validate_admission: AdmissionValidator | None = None,
|
|
529
739
|
project: Projector | None = None,
|
|
530
740
|
derivation_version: str = "v3.7-ingestion-1",
|
|
531
741
|
lease_seconds: float = 900.0,
|
|
@@ -533,6 +743,7 @@ class IngestionCommand:
|
|
|
533
743
|
self.repository = repository
|
|
534
744
|
self._write_queryable = write_queryable
|
|
535
745
|
self._materializer = materialize
|
|
746
|
+
self._validate_admission = validate_admission
|
|
536
747
|
self._projector = project
|
|
537
748
|
self._derivation_version = derivation_version
|
|
538
749
|
self._lease_seconds = max(1.0, float(lease_seconds))
|
|
@@ -603,13 +814,18 @@ class IngestionCommand:
|
|
|
603
814
|
self, request: IngestionRequest,
|
|
604
815
|
) -> tuple[IngestionOperation, bool]:
|
|
605
816
|
"""Submit once and report whether this call created the operation."""
|
|
817
|
+
# Trust/authentication and deterministic policy checks belong before
|
|
818
|
+
# the durable transaction. They may reject, log, or consult policy,
|
|
819
|
+
# but must never extend SQLite's writer critical section.
|
|
820
|
+
if self._validate_admission is not None:
|
|
821
|
+
self._validate_admission(request)
|
|
606
822
|
with self.repository.db.transaction():
|
|
607
823
|
operation, created = self.repository.create_with_status(request)
|
|
608
824
|
if operation.state is not IngestionState.RAW:
|
|
609
825
|
return operation, created
|
|
610
826
|
fact_ids = tuple(self._write_queryable(request, operation.operation_id))
|
|
611
827
|
if not fact_ids:
|
|
612
|
-
raise
|
|
828
|
+
raise IngestionRejectedError("ingestion produced no queryable facts")
|
|
613
829
|
receipt = self.repository.transition(
|
|
614
830
|
operation.operation_id,
|
|
615
831
|
expected=IngestionState.RAW,
|
|
@@ -624,10 +840,29 @@ class IngestionCommand:
|
|
|
624
840
|
with _materialization_lock(operation_id):
|
|
625
841
|
return self._materialize_locked(operation_id)
|
|
626
842
|
|
|
627
|
-
def _materialize_locked(
|
|
843
|
+
def _materialize_locked(
|
|
844
|
+
self,
|
|
845
|
+
operation_id: str,
|
|
846
|
+
*,
|
|
847
|
+
force: bool = False,
|
|
848
|
+
) -> IngestionOperation:
|
|
628
849
|
operation = self.repository.get(operation_id)
|
|
629
850
|
if operation.state is IngestionState.COMPLETE:
|
|
630
851
|
return operation
|
|
852
|
+
# Fix E: guard against re-attempting exhausted (dead-lettered) operations.
|
|
853
|
+
# claim_enriching increments the count before each real attempt, and
|
|
854
|
+
# finish_enriching dead-letters the failure whose count reaches the
|
|
855
|
+
# cap. A subsequent materialize() call sees count==cap and must not
|
|
856
|
+
# re-claim or insert another dead-letter row.
|
|
857
|
+
# ``force=True`` is the operator escape hatch used by retry() — it bypasses
|
|
858
|
+
# this guard so an admin can manually re-enqueue a dead-lettered operation.
|
|
859
|
+
if (
|
|
860
|
+
not force
|
|
861
|
+
and operation.state is IngestionState.FAILED
|
|
862
|
+
and operation.attempt_count >= _MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS
|
|
863
|
+
):
|
|
864
|
+
# Already dead-lettered — return FAILED without re-claiming.
|
|
865
|
+
return operation
|
|
631
866
|
if operation.state not in {
|
|
632
867
|
IngestionState.QUERYABLE,
|
|
633
868
|
IngestionState.ENRICHING,
|
|
@@ -757,9 +992,15 @@ class IngestionCommand:
|
|
|
757
992
|
)
|
|
758
993
|
|
|
759
994
|
def retry(self, operation_id: str) -> IngestionOperation:
|
|
995
|
+
"""Operator escape hatch: force-retry a FAILED operation regardless of
|
|
996
|
+
attempt_count. Bypasses the Fix E dead-letter guard so an admin can
|
|
997
|
+
manually re-enqueue an exhausted operation after configuration repair.
|
|
998
|
+
"""
|
|
760
999
|
operation = self.repository.get(operation_id)
|
|
761
1000
|
if operation.state is not IngestionState.FAILED:
|
|
762
1001
|
raise InvalidStateTransition(
|
|
763
1002
|
f"cannot retry operation in {operation.state.value}"
|
|
764
1003
|
)
|
|
765
|
-
|
|
1004
|
+
# force=True bypasses the _MAX_AUTOMATIC_MATERIALIZATION_ATTEMPTS guard.
|
|
1005
|
+
with _materialization_lock(operation_id):
|
|
1006
|
+
return self._materialize_locked(operation_id, force=True)
|
|
@@ -60,17 +60,42 @@ class MaintenanceScheduler:
|
|
|
60
60
|
return
|
|
61
61
|
self._running = True
|
|
62
62
|
self._schedule_next()
|
|
63
|
+
# v3.8.5: one-shot activation-cache GC ~90s after boot so an upgrade
|
|
64
|
+
# backlog (observed 83k expired rows) clears promptly instead of waiting
|
|
65
|
+
# a full interval — delayed past boot warmup so it never competes for
|
|
66
|
+
# the write lock during the startup window.
|
|
67
|
+
self._initial_gc_timer = threading.Timer(90.0, self._initial_cache_gc)
|
|
68
|
+
self._initial_gc_timer.daemon = True
|
|
69
|
+
self._initial_gc_timer.start()
|
|
63
70
|
logger.info(
|
|
64
71
|
"Maintenance scheduler started (interval=%dm)",
|
|
65
72
|
self._config.forgetting.scheduler_interval_minutes,
|
|
66
73
|
)
|
|
67
74
|
|
|
75
|
+
def _initial_cache_gc(self) -> None:
|
|
76
|
+
"""Best-effort one-shot activation-cache GC shortly after boot."""
|
|
77
|
+
if not self._running:
|
|
78
|
+
return
|
|
79
|
+
try:
|
|
80
|
+
deleted = self._db.cleanup_activation_cache()
|
|
81
|
+
if deleted > 0:
|
|
82
|
+
logger.info(
|
|
83
|
+
"Activation-cache GC (startup): %d expired rows removed",
|
|
84
|
+
deleted,
|
|
85
|
+
)
|
|
86
|
+
except Exception as exc:
|
|
87
|
+
logger.debug("Startup activation-cache GC skipped: %s", exc)
|
|
88
|
+
|
|
68
89
|
def stop(self) -> None:
|
|
69
90
|
"""Stop the scheduler. Idempotent."""
|
|
70
91
|
self._running = False
|
|
71
92
|
if self._timer is not None:
|
|
72
93
|
self._timer.cancel()
|
|
73
94
|
self._timer = None
|
|
95
|
+
_gc_timer = getattr(self, "_initial_gc_timer", None)
|
|
96
|
+
if _gc_timer is not None:
|
|
97
|
+
_gc_timer.cancel()
|
|
98
|
+
self._initial_gc_timer = None
|
|
74
99
|
logger.info("Maintenance scheduler stopped")
|
|
75
100
|
|
|
76
101
|
def _schedule_next(self) -> None:
|
|
@@ -125,9 +150,33 @@ class MaintenanceScheduler:
|
|
|
125
150
|
)
|
|
126
151
|
|
|
127
152
|
# V3.4.11: Graph pruning (remove orphan edges)
|
|
153
|
+
# v3.8.4-G: thread GraphPruningConfig params so dashboard changes
|
|
154
|
+
# persist and take effect without a daemon restart.
|
|
128
155
|
try:
|
|
129
156
|
from superlocalmemory.core.graph_pruner import prune_graph
|
|
130
|
-
|
|
157
|
+
gp = self._config.graph_pruning
|
|
158
|
+
if not gp.enabled:
|
|
159
|
+
logger.debug(
|
|
160
|
+
"Graph pruning disabled by config for %s — skipping",
|
|
161
|
+
profile_id,
|
|
162
|
+
)
|
|
163
|
+
else:
|
|
164
|
+
# Fix A: pass DatabaseManager directly → writes serialised through _lock
|
|
165
|
+
prune_stats = prune_graph(
|
|
166
|
+
self._db,
|
|
167
|
+
profile_id,
|
|
168
|
+
max_degree=gp.max_degree_per_node,
|
|
169
|
+
min_edge_weight=gp.min_edge_weight,
|
|
170
|
+
)
|
|
171
|
+
removed = prune_stats["total_before"] - prune_stats["total_after"]
|
|
172
|
+
if removed > 0:
|
|
173
|
+
logger.info(
|
|
174
|
+
"Graph pruning for %s: %d edges removed", profile_id, removed
|
|
175
|
+
)
|
|
176
|
+
except AttributeError:
|
|
177
|
+
# Older SLMConfig without graph_pruning field (upgrade safety)
|
|
178
|
+
from superlocalmemory.core.graph_pruner import prune_graph
|
|
179
|
+
prune_stats = prune_graph(self._db, profile_id)
|
|
131
180
|
removed = prune_stats["total_before"] - prune_stats["total_after"]
|
|
132
181
|
if removed > 0:
|
|
133
182
|
logger.info("Graph pruning for %s: %d edges removed", profile_id, removed)
|
|
@@ -171,6 +220,17 @@ class MaintenanceScheduler:
|
|
|
171
220
|
except Exception as exc:
|
|
172
221
|
logger.debug("Pending cleanup skipped: %s", exc)
|
|
173
222
|
|
|
223
|
+
# v3.8.5: GC the spreading-activation result cache. Neither cleanup path
|
|
224
|
+
# was ever wired in, so activation_cache grew without bound (observed
|
|
225
|
+
# 83k expired rows, oldest ~3.5 months). Batched + DB-wide (expiry is
|
|
226
|
+
# not profile-scoped), so it runs once per cycle rather than per profile.
|
|
227
|
+
try:
|
|
228
|
+
deleted = self._db.cleanup_activation_cache()
|
|
229
|
+
if deleted > 0:
|
|
230
|
+
logger.info("Activation-cache GC: %d expired rows removed", deleted)
|
|
231
|
+
except Exception as exc:
|
|
232
|
+
logger.debug("Activation-cache GC skipped: %s", exc)
|
|
233
|
+
|
|
174
234
|
self._schedule_next()
|
|
175
235
|
|
|
176
236
|
def _profile_ids(self) -> tuple[str, ...]:
|
|
@@ -42,6 +42,8 @@ def delete_fact_authorized(
|
|
|
42
42
|
*,
|
|
43
43
|
trusted_actor_id: str,
|
|
44
44
|
source_agent_id: str,
|
|
45
|
+
canonical_runtime: Any | None = None,
|
|
46
|
+
idempotency_key: str | None = None,
|
|
45
47
|
) -> dict[str, Any]:
|
|
46
48
|
"""Authorize, delete one profile-owned fact, then emit post hooks."""
|
|
47
49
|
profile_id, context = _context(
|
|
@@ -51,15 +53,23 @@ def delete_fact_authorized(
|
|
|
51
53
|
trusted_actor_id=trusted_actor_id,
|
|
52
54
|
source_agent_id=source_agent_id,
|
|
53
55
|
)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
56
|
+
if canonical_runtime is not None:
|
|
57
|
+
result = dict(canonical_runtime.delete_fact(
|
|
58
|
+
profile_id, fact_id, idempotency_key=idempotency_key,
|
|
59
|
+
))
|
|
60
|
+
if not result.get("ok"):
|
|
61
|
+
return {"ok": False, "error": f"Memory {fact_id} not found"}
|
|
62
|
+
content_preview = str(result.get("content_preview", ""))
|
|
63
|
+
else:
|
|
64
|
+
rows = engine._db.execute(
|
|
65
|
+
"SELECT content FROM atomic_facts "
|
|
66
|
+
"WHERE fact_id = ? AND profile_id = ? LIMIT 1",
|
|
67
|
+
(fact_id, profile_id),
|
|
68
|
+
)
|
|
69
|
+
if not rows:
|
|
70
|
+
return {"ok": False, "error": f"Memory {fact_id} not found"}
|
|
71
|
+
content_preview = dict(rows[0]).get("content", "")[:80]
|
|
72
|
+
engine._db.delete_fact(fact_id, profile_id=profile_id)
|
|
63
73
|
try:
|
|
64
74
|
from superlocalmemory.core.backend_orchestrator import get_orchestrator
|
|
65
75
|
orchestrator = get_orchestrator()
|
|
@@ -86,6 +96,8 @@ def update_fact_authorized(
|
|
|
86
96
|
*,
|
|
87
97
|
trusted_actor_id: str,
|
|
88
98
|
source_agent_id: str,
|
|
99
|
+
canonical_runtime: Any | None = None,
|
|
100
|
+
idempotency_key: str | None = None,
|
|
89
101
|
) -> dict[str, Any]:
|
|
90
102
|
"""Authorize a fact update and refresh semantic and lexical indexes."""
|
|
91
103
|
if not content or not content.strip():
|
|
@@ -120,7 +132,17 @@ def update_fact_authorized(
|
|
|
120
132
|
updates["fisher_variance"] = fisher_variance
|
|
121
133
|
except Exception as exc:
|
|
122
134
|
logger.warning("UPDATE embedding refresh failed: %s", exc)
|
|
123
|
-
|
|
135
|
+
if canonical_runtime is not None:
|
|
136
|
+
result = dict(canonical_runtime.update_fact(
|
|
137
|
+
profile_id,
|
|
138
|
+
fact_id,
|
|
139
|
+
updates,
|
|
140
|
+
idempotency_key=idempotency_key,
|
|
141
|
+
))
|
|
142
|
+
if not result.get("ok"):
|
|
143
|
+
return {"ok": False, "error": f"Memory {fact_id} not found"}
|
|
144
|
+
else:
|
|
145
|
+
engine._db.update_fact(fact_id, updates, profile_id=profile_id)
|
|
124
146
|
try:
|
|
125
147
|
from superlocalmemory.core.backend_orchestrator import get_orchestrator
|
|
126
148
|
orchestrator = get_orchestrator()
|