superlocalmemory 4.1.4 → 4.1.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/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +68 -0
- package/README.md +3 -3
- 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 +2 -2
- 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 +2 -2
- 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-governance/SKILL.md +1 -1
- package/plugin-src/skills/slm-graph/SKILL.md +1 -1
- package/plugin-src/skills/slm-loop/SKILL.md +1 -1
- package/plugin-src/skills/slm-mesh/SKILL.md +2 -2
- package/plugin-src/skills/slm-profile/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-scope/SKILL.md +1 -1
- package/plugin-src/skills/slm-session/SKILL.md +2 -2
- package/plugin-src/skills/slm-status/SKILL.md +1 -1
- package/pyproject.toml +1 -1
- package/src/superlocalmemory/__init__.py +1 -1
- package/src/superlocalmemory/cli/diagnostics_cmd.py +74 -1
- package/src/superlocalmemory/cli/main.py +12 -0
- package/src/superlocalmemory/core/maintenance_scheduler.py +36 -0
- package/src/superlocalmemory/core/remember_runtime.py +12 -1
- package/src/superlocalmemory/encoding/fact_extractor.py +7 -3
- package/src/superlocalmemory/mcp/session_binding.py +7 -1
- package/src/superlocalmemory/reliability/__init__.py +45 -0
- package/src/superlocalmemory/reliability/join_liveness.py +301 -0
- package/src/superlocalmemory/reliability/prior_distance.py +243 -0
- package/src/superlocalmemory/server/routes/backup.py +1 -1
|
@@ -34,7 +34,13 @@ __all__ = ["resolve_session_id", "SESSION_ENV_VARS"]
|
|
|
34
34
|
|
|
35
35
|
#: Checked in order. Hosts set one or the other; SLM's own takes precedence so a
|
|
36
36
|
#: user can override a host that sets its variable to something unhelpful.
|
|
37
|
-
|
|
37
|
+
#: ``CLAUDE_CODE_SESSION_ID`` is the actual variable Claude Code's MCP
|
|
38
|
+
#: subprocess environment carries — verified on a live daemon 2026-08-24,
|
|
39
|
+
#: this pipeline settled 6013/6039 outcomes at the neutral 0.5 fallback
|
|
40
|
+
#: because the old two-name list never matched it, and every recall fell
|
|
41
|
+
#: through to the synthetic ``mcp:<agent_id>`` id that step 4 deliberately
|
|
42
|
+
#: excludes from matching.
|
|
43
|
+
SESSION_ENV_VARS = ("SLM_SESSION_ID", "CLAUDE_SESSION_ID", "CLAUDE_CODE_SESSION_ID")
|
|
38
44
|
|
|
39
45
|
|
|
40
46
|
def resolve_session_id(
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Copyright (c) 2026 Varun Pratap Bhardwaj / Qualixar
|
|
2
|
+
# Licensed under AGPL-3.0-or-later - see LICENSE file
|
|
3
|
+
# Part of SuperLocalMemory | https://qualixar.com | https://varunpratap.com
|
|
4
|
+
|
|
5
|
+
"""Checks that ask whether a mechanism is *effective*, not merely present.
|
|
6
|
+
|
|
7
|
+
Three questions get confused in a system this size:
|
|
8
|
+
|
|
9
|
+
* **Implemented** — the code exists. A grep answers this.
|
|
10
|
+
* **Reachable** — something calls it. A call-graph trace answers this.
|
|
11
|
+
* **Effective** — it has actually changed an outcome against real data.
|
|
12
|
+
**Neither of the above answers this.** Only querying the store does.
|
|
13
|
+
|
|
14
|
+
A mechanism can pass the first two questions for months and fail the third
|
|
15
|
+
silently: a learner whose reward channel emits a constant still records plays,
|
|
16
|
+
and a conditional path guarded by a missing column still appears in coverage.
|
|
17
|
+
Nothing raises, nothing logs, and every file is present.
|
|
18
|
+
|
|
19
|
+
The two checks here answer the third question directly.
|
|
20
|
+
|
|
21
|
+
* :mod:`.prior_distance` — has a Bayesian learner's posterior actually moved
|
|
22
|
+
away from its prior?
|
|
23
|
+
* :mod:`.join_liveness` — has a schema-guarded code path ever executed against
|
|
24
|
+
this store, and if not, which requirement is missing?
|
|
25
|
+
|
|
26
|
+
Both are read-only, both are fail-soft, and neither is on a hot path.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from superlocalmemory.reliability.join_liveness import (
|
|
30
|
+
GuardVerdict,
|
|
31
|
+
check_schema_guards,
|
|
32
|
+
)
|
|
33
|
+
from superlocalmemory.reliability.prior_distance import (
|
|
34
|
+
DEFAULT_MIN_OBSERVATIONS,
|
|
35
|
+
LearnerVerdict,
|
|
36
|
+
check_beta_learners,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"DEFAULT_MIN_OBSERVATIONS",
|
|
41
|
+
"GuardVerdict",
|
|
42
|
+
"LearnerVerdict",
|
|
43
|
+
"check_beta_learners",
|
|
44
|
+
"check_schema_guards",
|
|
45
|
+
]
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# Copyright (c) 2026 Varun Pratap Bhardwaj / Qualixar
|
|
2
|
+
# Licensed under AGPL-3.0-or-later - see LICENSE file
|
|
3
|
+
# Part of SuperLocalMemory | https://qualixar.com | https://varunpratap.com
|
|
4
|
+
|
|
5
|
+
"""Can a schema-guarded code path run against this store, and has it had the data?
|
|
6
|
+
|
|
7
|
+
A note on what this proves, because the honest scope is narrower than the
|
|
8
|
+
convenient phrasing. The check reads the schema: it establishes whether the
|
|
9
|
+
guard's requirements are present *now*, and therefore whether the path is
|
|
10
|
+
reachable at all. It does not read an execution history, so a satisfied guard
|
|
11
|
+
means "this would execute", not "this has executed". The inference to "never
|
|
12
|
+
executed" is sound only in the other direction -- if a required column is absent
|
|
13
|
+
from a store that has been in service, the guarded path cannot have run against
|
|
14
|
+
it -- and that is the direction the findings rely on.
|
|
15
|
+
|
|
16
|
+
Some features are wired behind a guard that asks the schema a question before
|
|
17
|
+
doing any work — "is this table here, does that column exist" — and fall back
|
|
18
|
+
silently when the answer is no. The fallback is correct behaviour: it is what
|
|
19
|
+
keeps an old store openable. But it means a feature can be implemented, called
|
|
20
|
+
on the hot path, and covered by tests, while never once executing against real
|
|
21
|
+
data. Static analysis passes. A call-graph trace passes. Coverage passes. The
|
|
22
|
+
guard returns ``False`` and the feature is arithmetically absent.
|
|
23
|
+
|
|
24
|
+
Two things make that failure hard to see from inside the code:
|
|
25
|
+
|
|
26
|
+
1. **The guard is doing its job.** There is no error to raise. Falling back is
|
|
27
|
+
the designed response to a missing column.
|
|
28
|
+
2. **The fallback is often a neutral value**, which composes into an identity.
|
|
29
|
+
A decay-rate multiplier that falls back to a trust of 1.0 collapses
|
|
30
|
+
``lambda * (1 + kappa * (1 - trust))`` to ``lambda`` — the feature is on, and
|
|
31
|
+
it computes exactly what having no feature would compute.
|
|
32
|
+
|
|
33
|
+
So this check does two things a plain schema assertion does not. It records
|
|
34
|
+
whether each named guard **passes right now**, and when a guard fails it looks
|
|
35
|
+
for the required data **elsewhere in the store** — because the common case is
|
|
36
|
+
not that the data is missing, it is that the guard is asking the wrong table.
|
|
37
|
+
|
|
38
|
+
A guard reported as ``SATISFIED_ELSEWHERE`` is the most actionable outcome
|
|
39
|
+
available: the feature is one re-keyed join away from working, and no backfill
|
|
40
|
+
or migration is required.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import logging
|
|
46
|
+
import sqlite3
|
|
47
|
+
from dataclasses import dataclass, field
|
|
48
|
+
from typing import Any
|
|
49
|
+
|
|
50
|
+
logger = logging.getLogger("superlocalmemory.reliability.join_liveness")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class Requirement:
|
|
55
|
+
"""One schema object a guard needs: a table, optionally a column on it."""
|
|
56
|
+
|
|
57
|
+
table: str
|
|
58
|
+
column: str | None = None
|
|
59
|
+
|
|
60
|
+
def __str__(self) -> str:
|
|
61
|
+
return f"{self.table}.{self.column}" if self.column else self.table
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Guard:
|
|
66
|
+
"""A named conditional path and the schema it requires to execute."""
|
|
67
|
+
|
|
68
|
+
name: str
|
|
69
|
+
describes: str
|
|
70
|
+
requires: tuple[Requirement, ...]
|
|
71
|
+
#: What the feature computes when the guard fails, in words. Recording this
|
|
72
|
+
#: is the difference between "a feature is off" and "a feature is off and
|
|
73
|
+
#: indistinguishable from not having it".
|
|
74
|
+
fallback_behaviour: str
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class GuardVerdict:
|
|
79
|
+
name: str
|
|
80
|
+
describes: str
|
|
81
|
+
#: LIVE = requirements present, so the path is reachable now. DEAD / #: SATISFIED_ELSEWHERE = a requirement is absent, so the path cannot have run
|
|
82
|
+
#: against this store. LIVE is NOT evidence of past execution.
|
|
83
|
+
verdict: str
|
|
84
|
+
missing: tuple[str, ...] = field(default=())
|
|
85
|
+
found_elsewhere: tuple[tuple[str, str, int, float], ...] = field(default=())
|
|
86
|
+
detail: str = ""
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def is_live(self) -> bool:
|
|
90
|
+
return self.verdict == "LIVE"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
#: Guards worth reporting on. Each entry names a real conditional in the code,
|
|
94
|
+
#: so that a reader can go from this list to the line that asks the question.
|
|
95
|
+
GUARDS: tuple[Guard, ...] = (
|
|
96
|
+
Guard(
|
|
97
|
+
name="trust_weighted_forgetting",
|
|
98
|
+
describes=(
|
|
99
|
+
"learning/forgetting_scheduler.py::_has_trust_tables — gates the "
|
|
100
|
+
"per-fact trust lookup that modulates the decay rate"
|
|
101
|
+
),
|
|
102
|
+
requires=(
|
|
103
|
+
Requirement("trust_scores"),
|
|
104
|
+
Requirement("atomic_facts", "created_by"),
|
|
105
|
+
),
|
|
106
|
+
fallback_behaviour=(
|
|
107
|
+
"every fact takes trust = 1.0, so lambda_eff collapses to "
|
|
108
|
+
"lambda_base and the decay rate is identical to no trust weighting"
|
|
109
|
+
),
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _table_exists(conn: sqlite3.Connection, table: str) -> bool:
|
|
115
|
+
return (
|
|
116
|
+
conn.execute(
|
|
117
|
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1",
|
|
118
|
+
(table,),
|
|
119
|
+
).fetchone()
|
|
120
|
+
is not None
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _columns(conn: sqlite3.Connection, table: str) -> set[str]:
|
|
125
|
+
try:
|
|
126
|
+
return {r[1] for r in conn.execute(f'PRAGMA table_info("{table}")')}
|
|
127
|
+
except sqlite3.Error:
|
|
128
|
+
return set()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _satisfied(conn: sqlite3.Connection, requirement: Requirement) -> bool:
|
|
132
|
+
if not _table_exists(conn, requirement.table):
|
|
133
|
+
return False
|
|
134
|
+
if requirement.column is None:
|
|
135
|
+
return True
|
|
136
|
+
return requirement.column in _columns(conn, requirement.table)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _look_elsewhere(
|
|
140
|
+
conn: sqlite3.Connection,
|
|
141
|
+
column: str,
|
|
142
|
+
*,
|
|
143
|
+
join_target: str | None = None,
|
|
144
|
+
join_key: str = "fact_id",
|
|
145
|
+
) -> list[tuple[str, str, int]]:
|
|
146
|
+
"""Find other tables carrying ``column``, with a populated-row count.
|
|
147
|
+
|
|
148
|
+
This is the part that turns a failed guard into a fix. A column the guard
|
|
149
|
+
could not find on its own table is often present on a neighbouring one,
|
|
150
|
+
already populated.
|
|
151
|
+
|
|
152
|
+
**A populated count is not coverage, and reporting it alone overstates the
|
|
153
|
+
remedy.** A provenance-style table can carry a value on every one of its own
|
|
154
|
+
rows while describing only part of the set the join needs: rows can be
|
|
155
|
+
missing for older entities entirely. When ``join_target`` is given, the
|
|
156
|
+
coverage fraction over that table is measured and returned, because the
|
|
157
|
+
honest question is not "does this column exist somewhere" but "how much of
|
|
158
|
+
what the guard needs would the re-keyed join actually resolve".
|
|
159
|
+
"""
|
|
160
|
+
out: list[tuple[str, str, int]] = []
|
|
161
|
+
tables = [
|
|
162
|
+
r[0]
|
|
163
|
+
for r in conn.execute(
|
|
164
|
+
"SELECT name FROM sqlite_master WHERE type='table' "
|
|
165
|
+
"AND name NOT LIKE 'sqlite_%'",
|
|
166
|
+
)
|
|
167
|
+
]
|
|
168
|
+
for table in tables:
|
|
169
|
+
if column not in _columns(conn, table):
|
|
170
|
+
continue
|
|
171
|
+
try:
|
|
172
|
+
populated = conn.execute(
|
|
173
|
+
f'SELECT COUNT(*) FROM "{table}" '
|
|
174
|
+
f'WHERE "{column}" IS NOT NULL AND TRIM("{column}") <> \'\'',
|
|
175
|
+
).fetchone()[0]
|
|
176
|
+
except sqlite3.Error:
|
|
177
|
+
populated = 0
|
|
178
|
+
covered = -1
|
|
179
|
+
if join_target and join_target != table:
|
|
180
|
+
try:
|
|
181
|
+
total = conn.execute(
|
|
182
|
+
f'SELECT COUNT(*) FROM "{join_target}"',
|
|
183
|
+
).fetchone()[0]
|
|
184
|
+
if total:
|
|
185
|
+
hit = conn.execute(
|
|
186
|
+
f'SELECT COUNT(*) FROM "{join_target}" t WHERE EXISTS ('
|
|
187
|
+
f' SELECT 1 FROM "{table}" s WHERE s."{join_key}" = t."{join_key}"'
|
|
188
|
+
f' AND s."{column}" IS NOT NULL AND TRIM(s."{column}") <> \'\')',
|
|
189
|
+
).fetchone()[0]
|
|
190
|
+
covered = round(100.0 * hit / total, 1)
|
|
191
|
+
except sqlite3.Error:
|
|
192
|
+
covered = -1
|
|
193
|
+
out.append((table, column, int(populated), covered))
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _evaluate(conn: sqlite3.Connection, guard: Guard) -> GuardVerdict:
|
|
198
|
+
missing = [str(r) for r in guard.requires if not _satisfied(conn, r)]
|
|
199
|
+
if not missing:
|
|
200
|
+
return GuardVerdict(
|
|
201
|
+
name=guard.name,
|
|
202
|
+
describes=guard.describes,
|
|
203
|
+
verdict="LIVE",
|
|
204
|
+
detail=(
|
|
205
|
+
"Every requirement is present, so the guarded path is reachable "
|
|
206
|
+
"on this store. This is schema evidence, not execution history: "
|
|
207
|
+
"it does not establish that the path has ever actually run."
|
|
208
|
+
),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
elsewhere: list[tuple[str, str, int, float]] = []
|
|
212
|
+
for requirement in guard.requires:
|
|
213
|
+
if requirement.column and not _satisfied(conn, requirement):
|
|
214
|
+
for found in _look_elsewhere(
|
|
215
|
+
conn, requirement.column, join_target=requirement.table,
|
|
216
|
+
):
|
|
217
|
+
if found[0] != requirement.table:
|
|
218
|
+
elsewhere.append(found)
|
|
219
|
+
|
|
220
|
+
populated = [e for e in elsewhere if e[2] > 0]
|
|
221
|
+
if populated:
|
|
222
|
+
# Rank by coverage of the guarded table, falling back to row count only
|
|
223
|
+
# when coverage could not be measured. Picking the largest table instead
|
|
224
|
+
# would recommend a 4,000-row partial source over a smaller complete one.
|
|
225
|
+
best = max(populated, key=lambda e: (e[3], e[2]))
|
|
226
|
+
cov = best[3]
|
|
227
|
+
if cov < 0:
|
|
228
|
+
remedy = (
|
|
229
|
+
f"Re-keying the join onto that table would make the path "
|
|
230
|
+
f"executable; coverage over the guarded table could not be "
|
|
231
|
+
f"measured here, so confirm it before relying on the remedy."
|
|
232
|
+
)
|
|
233
|
+
elif cov >= 99.5:
|
|
234
|
+
remedy = (
|
|
235
|
+
f"That table covers {cov}% of the rows the guard needs, so "
|
|
236
|
+
f"re-keying the join makes the path live without a backfill."
|
|
237
|
+
)
|
|
238
|
+
else:
|
|
239
|
+
remedy = (
|
|
240
|
+
f"That table covers only {cov}% of the rows the guard needs. "
|
|
241
|
+
f"Re-keying the join makes the path executable for those rows "
|
|
242
|
+
f"and leaves the remainder on the same fallback, so this is a "
|
|
243
|
+
f"partial remedy and a backfill decision, not a free fix."
|
|
244
|
+
)
|
|
245
|
+
return GuardVerdict(
|
|
246
|
+
name=guard.name,
|
|
247
|
+
describes=guard.describes,
|
|
248
|
+
verdict="SATISFIED_ELSEWHERE",
|
|
249
|
+
missing=tuple(missing),
|
|
250
|
+
found_elsewhere=tuple(elsewhere),
|
|
251
|
+
detail=(
|
|
252
|
+
f"The guard requires {', '.join(missing)}, which is absent, so "
|
|
253
|
+
f"the path has never executed against this store — "
|
|
254
|
+
f"{guard.fallback_behaviour}. The data it needs is present on "
|
|
255
|
+
f"{best[0]}.{best[1]} with {best[2]} populated rows. {remedy}"
|
|
256
|
+
),
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
return GuardVerdict(
|
|
260
|
+
name=guard.name,
|
|
261
|
+
describes=guard.describes,
|
|
262
|
+
verdict="DEAD",
|
|
263
|
+
missing=tuple(missing),
|
|
264
|
+
detail=(
|
|
265
|
+
f"The guard requires {', '.join(missing)}, which is absent from "
|
|
266
|
+
f"this store and not carried by any other table, so the path has "
|
|
267
|
+
f"never executed — {guard.fallback_behaviour}."
|
|
268
|
+
),
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def check_schema_guards(
|
|
273
|
+
memory_db: Any, *, guards: tuple[Guard, ...] = GUARDS,
|
|
274
|
+
) -> list[GuardVerdict]:
|
|
275
|
+
"""Report, per registered guard, whether its path can run on this store.
|
|
276
|
+
|
|
277
|
+
``memory_db`` may be a path or an open connection. Read-only, and fail-soft:
|
|
278
|
+
an error yields an empty list, because a diagnostic must never be the reason
|
|
279
|
+
something breaks.
|
|
280
|
+
"""
|
|
281
|
+
owns_connection = not isinstance(memory_db, sqlite3.Connection)
|
|
282
|
+
conn: sqlite3.Connection | None = None
|
|
283
|
+
try:
|
|
284
|
+
conn = (
|
|
285
|
+
sqlite3.connect(f"file:{memory_db}?mode=ro", uri=True)
|
|
286
|
+
if owns_connection
|
|
287
|
+
else memory_db
|
|
288
|
+
)
|
|
289
|
+
return [_evaluate(conn, guard) for guard in guards]
|
|
290
|
+
except Exception:
|
|
291
|
+
logger.debug("join-liveness check skipped", exc_info=True)
|
|
292
|
+
return []
|
|
293
|
+
finally:
|
|
294
|
+
if owns_connection and conn is not None:
|
|
295
|
+
try:
|
|
296
|
+
conn.close()
|
|
297
|
+
except Exception:
|
|
298
|
+
pass
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
__all__ = ["GUARDS", "Guard", "GuardVerdict", "Requirement", "check_schema_guards"]
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# Copyright (c) 2026 Varun Pratap Bhardwaj / Qualixar
|
|
2
|
+
# Licensed under AGPL-3.0-or-later - see LICENSE file
|
|
3
|
+
# Part of SuperLocalMemory | https://qualixar.com | https://varunpratap.com
|
|
4
|
+
|
|
5
|
+
"""Has a Bayesian learner's posterior actually moved off its prior?
|
|
6
|
+
|
|
7
|
+
A Thompson-sampling selector over Beta posteriors records a play, applies a
|
|
8
|
+
reward, and reports both. None of that tells you whether it learned anything.
|
|
9
|
+
Its own counters cannot: a reward channel that emits one constant value
|
|
10
|
+
increments the posterior on every play, so the play count rises, the timestamps
|
|
11
|
+
advance, and the dashboard looks alive while the distribution never moves.
|
|
12
|
+
|
|
13
|
+
This is not a hypothetical. A Beta posterior updated as
|
|
14
|
+
``alpha += r; beta += (1 - r)`` is stationary in mean for exactly one reward
|
|
15
|
+
value: ``r = 0.5``. And that value is the usual neutral fallback when a reward
|
|
16
|
+
cannot be attributed to a play. So the failure that produces *no learning at
|
|
17
|
+
all* is also the failure that produces *the most normal-looking counters*.
|
|
18
|
+
|
|
19
|
+
The signature is exact, not statistical. With a ``Beta(a0, b0)`` prior and *n*
|
|
20
|
+
observations all equal to 0.5::
|
|
21
|
+
|
|
22
|
+
alpha - a0 == beta - b0 == n * 0.5
|
|
23
|
+
|
|
24
|
+
0.5 is exactly representable in binary floating point, so ``n * 0.5`` is exact
|
|
25
|
+
for any plausible *n*. A learner matching that identity on every unit has
|
|
26
|
+
provably received the neutral value every single time — there is no sampling
|
|
27
|
+
noise to argue about, and one run is enough to establish it.
|
|
28
|
+
|
|
29
|
+
What this check does NOT claim: that a moving posterior is a *good* one. Motion
|
|
30
|
+
off the prior is necessary for learning, not sufficient. This distinguishes
|
|
31
|
+
"receiving signal" from "receiving nothing", which is the distinction the
|
|
32
|
+
learner's own metrics cannot make.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import logging
|
|
38
|
+
import sqlite3
|
|
39
|
+
from dataclasses import dataclass, field
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger("superlocalmemory.reliability.prior_distance")
|
|
43
|
+
|
|
44
|
+
#: Below this many observations in total, a posterior sitting at its prior is
|
|
45
|
+
#: expected rather than suspicious, so no verdict is issued.
|
|
46
|
+
DEFAULT_MIN_OBSERVATIONS = 20
|
|
47
|
+
|
|
48
|
+
#: And below this many observations *per unit*. An aggregate floor alone lets a
|
|
49
|
+
#: store with many units and few observations report STALLED on units that were
|
|
50
|
+
#: never played at all.
|
|
51
|
+
_MIN_OBSERVATIONS_PER_UNIT = 2.0
|
|
52
|
+
|
|
53
|
+
#: Distance from the prior mean below which a unit counts as unmoved. Kept well
|
|
54
|
+
#: above float noise so that a genuinely tiny update is not reported as none.
|
|
55
|
+
_MEAN_EPSILON = 1e-9
|
|
56
|
+
|
|
57
|
+
#: Beta learners in this store, as (table, unit column, observation column).
|
|
58
|
+
#: Each is a Beta(1, 1) posterior over a named unit.
|
|
59
|
+
_BETA_LEARNERS: tuple[tuple[str, str, str | None], ...] = (
|
|
60
|
+
("bandit_arms", "arm_id", "plays"),
|
|
61
|
+
("source_quality", "source_id", None),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
_PRIOR_ALPHA = 1.0
|
|
65
|
+
_PRIOR_BETA = 1.0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class LearnerVerdict:
|
|
70
|
+
"""One Beta learner, and whether its posterior has moved."""
|
|
71
|
+
|
|
72
|
+
table: str
|
|
73
|
+
units: int
|
|
74
|
+
units_at_prior_mean: int
|
|
75
|
+
units_matching_neutral_identity: int
|
|
76
|
+
observations: int
|
|
77
|
+
verdict: str
|
|
78
|
+
detail: str
|
|
79
|
+
sample: tuple[tuple[str, float, float], ...] = field(default=())
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def is_stalled(self) -> bool:
|
|
83
|
+
return self.verdict == "STALLED"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _table_exists(conn: sqlite3.Connection, table: str) -> bool:
|
|
87
|
+
row = conn.execute(
|
|
88
|
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1",
|
|
89
|
+
(table,),
|
|
90
|
+
).fetchone()
|
|
91
|
+
return row is not None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _columns(conn: sqlite3.Connection, table: str) -> set[str]:
|
|
95
|
+
return {r[1] for r in conn.execute(f'PRAGMA table_info("{table}")')}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _inspect_learner(
|
|
99
|
+
conn: sqlite3.Connection,
|
|
100
|
+
table: str,
|
|
101
|
+
unit_column: str,
|
|
102
|
+
observation_column: str | None,
|
|
103
|
+
*,
|
|
104
|
+
min_observations: int,
|
|
105
|
+
) -> LearnerVerdict | None:
|
|
106
|
+
"""Inspect one Beta learner. Returns None when the table is absent."""
|
|
107
|
+
if not _table_exists(conn, table):
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
available = _columns(conn, table)
|
|
111
|
+
if not {"alpha", "beta"}.issubset(available):
|
|
112
|
+
return None
|
|
113
|
+
unit = unit_column if unit_column in available else "rowid"
|
|
114
|
+
obs_col = observation_column if (observation_column or "") in available else None
|
|
115
|
+
|
|
116
|
+
select = f'SELECT "{unit}", alpha, beta'
|
|
117
|
+
select += f', "{obs_col}"' if obs_col else ", NULL"
|
|
118
|
+
rows = conn.execute(f'{select} FROM "{table}"').fetchall()
|
|
119
|
+
if not rows:
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
units = len(rows)
|
|
123
|
+
at_prior_mean = 0
|
|
124
|
+
neutral_identity = 0
|
|
125
|
+
observations = 0
|
|
126
|
+
for _unit, alpha, beta, obs in rows:
|
|
127
|
+
alpha = float(alpha or 0.0)
|
|
128
|
+
beta = float(beta or 0.0)
|
|
129
|
+
total = alpha + beta
|
|
130
|
+
if total > 0 and abs(alpha / total - 0.5) < _MEAN_EPSILON:
|
|
131
|
+
at_prior_mean += 1
|
|
132
|
+
n = int(obs) if obs is not None else None
|
|
133
|
+
if n is None:
|
|
134
|
+
# No per-unit observation count. Infer it from the identity itself:
|
|
135
|
+
# n = (alpha - a0) / 0.5 only holds if every reward was neutral, so
|
|
136
|
+
# this is checked, never assumed.
|
|
137
|
+
candidate = (alpha - _PRIOR_ALPHA) * 2.0
|
|
138
|
+
n = int(round(candidate)) if candidate >= 0 else 0
|
|
139
|
+
observations += n
|
|
140
|
+
if n > 0 and (
|
|
141
|
+
abs((alpha - _PRIOR_ALPHA) - n * 0.5) < _MEAN_EPSILON
|
|
142
|
+
and abs((beta - _PRIOR_BETA) - n * 0.5) < _MEAN_EPSILON
|
|
143
|
+
):
|
|
144
|
+
neutral_identity += 1
|
|
145
|
+
|
|
146
|
+
sample = tuple(
|
|
147
|
+
(str(r[0]), float(r[1] or 0.0), float(r[2] or 0.0)) for r in rows[:3]
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# The floor has to bind per unit, not in aggregate. 165 arms sharing 20
|
|
151
|
+
# observations leaves most of them untouched at exactly the prior, which
|
|
152
|
+
# satisfies the unmoved test for a reason that carries no information. A
|
|
153
|
+
# verdict of STALLED must mean "measured inert", never "too sparse to tell".
|
|
154
|
+
per_unit = observations / units if units else 0.0
|
|
155
|
+
if observations < min_observations or per_unit < _MIN_OBSERVATIONS_PER_UNIT:
|
|
156
|
+
verdict = "INSUFFICIENT_DATA"
|
|
157
|
+
detail = (
|
|
158
|
+
f"{observations} observations across {units} units "
|
|
159
|
+
f"({per_unit:.2f} per unit) is too sparse for an unmoved posterior to "
|
|
160
|
+
f"mean anything; the floors are {min_observations} in total and "
|
|
161
|
+
f"{_MIN_OBSERVATIONS_PER_UNIT:g} per unit."
|
|
162
|
+
)
|
|
163
|
+
elif neutral_identity == units:
|
|
164
|
+
verdict = "STALLED"
|
|
165
|
+
detail = (
|
|
166
|
+
f"All {units} units satisfy (alpha-{_PRIOR_ALPHA:g}) == "
|
|
167
|
+
f"(beta-{_PRIOR_BETA:g}) == n/2 exactly across {observations} "
|
|
168
|
+
f"observations, so the rewards sum to exactly n/2 on every unit and "
|
|
169
|
+
f"each posterior mean is still {0.5}. No unit has acquired any "
|
|
170
|
+
f"preference. Note the identity constrains the SUM: it is also "
|
|
171
|
+
f"satisfied by a symmetric non-neutral stream, so confirm against a "
|
|
172
|
+
f"per-observation record before concluding the reward was constant."
|
|
173
|
+
)
|
|
174
|
+
elif at_prior_mean == units:
|
|
175
|
+
verdict = "STALLED"
|
|
176
|
+
detail = (
|
|
177
|
+
f"All {units} units sit at posterior mean 0.5 after {observations} "
|
|
178
|
+
f"observations, without matching the exact neutral identity. The "
|
|
179
|
+
f"updates are symmetric but not uniformly 0.5 — inspect the reward "
|
|
180
|
+
f"source."
|
|
181
|
+
)
|
|
182
|
+
else:
|
|
183
|
+
moved = units - at_prior_mean
|
|
184
|
+
verdict = "MOVING"
|
|
185
|
+
detail = (
|
|
186
|
+
f"{moved} of {units} units have moved off the prior mean across "
|
|
187
|
+
f"{observations} observations."
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
return LearnerVerdict(
|
|
191
|
+
table=table,
|
|
192
|
+
units=units,
|
|
193
|
+
units_at_prior_mean=at_prior_mean,
|
|
194
|
+
units_matching_neutral_identity=neutral_identity,
|
|
195
|
+
observations=observations,
|
|
196
|
+
verdict=verdict,
|
|
197
|
+
detail=detail,
|
|
198
|
+
sample=sample,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def check_beta_learners(
|
|
203
|
+
learning_db: Any,
|
|
204
|
+
*,
|
|
205
|
+
min_observations: int = DEFAULT_MIN_OBSERVATIONS,
|
|
206
|
+
) -> list[LearnerVerdict]:
|
|
207
|
+
"""Report, per Beta learner in ``learning_db``, whether it has learned.
|
|
208
|
+
|
|
209
|
+
``learning_db`` may be a path or an open :class:`sqlite3.Connection`. The
|
|
210
|
+
database is only read. Fail-soft: any error yields an empty list and a log
|
|
211
|
+
line, because a diagnostic must never be the reason something breaks.
|
|
212
|
+
"""
|
|
213
|
+
owns_connection = not isinstance(learning_db, sqlite3.Connection)
|
|
214
|
+
conn: sqlite3.Connection | None = None
|
|
215
|
+
try:
|
|
216
|
+
if owns_connection:
|
|
217
|
+
conn = sqlite3.connect(f"file:{learning_db}?mode=ro", uri=True)
|
|
218
|
+
else:
|
|
219
|
+
conn = learning_db
|
|
220
|
+
out: list[LearnerVerdict] = []
|
|
221
|
+
for table, unit_column, observation_column in _BETA_LEARNERS:
|
|
222
|
+
verdict = _inspect_learner(
|
|
223
|
+
conn,
|
|
224
|
+
table,
|
|
225
|
+
unit_column,
|
|
226
|
+
observation_column,
|
|
227
|
+
min_observations=min_observations,
|
|
228
|
+
)
|
|
229
|
+
if verdict is not None:
|
|
230
|
+
out.append(verdict)
|
|
231
|
+
return out
|
|
232
|
+
except Exception:
|
|
233
|
+
logger.debug("prior-distance check skipped", exc_info=True)
|
|
234
|
+
return []
|
|
235
|
+
finally:
|
|
236
|
+
if owns_connection and conn is not None:
|
|
237
|
+
try:
|
|
238
|
+
conn.close()
|
|
239
|
+
except Exception:
|
|
240
|
+
pass
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
__all__ = ["DEFAULT_MIN_OBSERVATIONS", "LearnerVerdict", "check_beta_learners"]
|
|
@@ -737,7 +737,7 @@ a { color: #00D4AA; }
|
|
|
737
737
|
<p class="sub">Back up your memories to a private GitHub repository.</p>
|
|
738
738
|
|
|
739
739
|
<label>Personal Access Token</label>
|
|
740
|
-
<input type="password" id="pat" placeholder="
|
|
740
|
+
<input type="password" id="pat" placeholder="GitHub personal access token">
|
|
741
741
|
|
|
742
742
|
<label>Repository Name</label>
|
|
743
743
|
<input type="text" id="repo" value="slm-backup" placeholder="slm-backup">
|