Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
emrg: usage anchor — unconditional bias-shift heartbeat + planted-fire assertions (issue #1072) by how2how2how2-arch · Pull Request #1073 · argszero/emrg · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' emrg: usage anchor — unconditional bias-shift heartbeat + planted-fire assertions (issue #1072) by how2how2how2-arch · Pull Request #1073 · argszero/emrg · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' emrg: usage anchor — unconditional bias-shift heartbeat + planted-fire assertions (issue #1072) by how2how2how2-arch · Pull Request #1073 · argszero/emrg · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' emrg: usage anchor — unconditional bias-shift heartbeat + planted-fire assertions (issue #1072) by how2how2how2-arch · Pull Request #1073 · argszero/emrg · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' emrg: usage anchor — unconditional bias-shift heartbeat + planted-fire assertions (issue #1072) by how2how2how2-arch · Pull Request #1073 · argszero/emrg · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); emrg: usage anchor — unconditional bias-shift heartbeat + planted-fire assertions (issue #1072) by how2how2how2-arch · Pull Request #1073 · argszero/emrg · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions emrg/server/daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -3119,6 +3119,20 @@ def _detect_silent_anchor_drift(self, session, real_pt: int, estimate: int) -> N
if old_bias <= 0:
return
shift = abs(new_bias - old_bias) / old_bias
# Issue #1072 (heinrichneb, Dev.to 3dlo4): make "never fired"
# measurable — log EVERY computed shift unconditionally so the
# detector's heartbeat is visible in emrgd.log (grep
# "anchor-bias-heartbeat"), distinguishing "detector runs, providers
# stable" from "detector dead". The warning below stays reserved for
# actual drift.
logger.debug(
"anchor-bias-heartbeat session=%s bias_shift=%.4f threshold=%.2f "
"old_bias=%.3f new_bias=%.3f — %s",
session.session_id, shift, _SILENT_DRIFT_THRESHOLD,
old_bias, new_bias,
"within threshold, no drift"
if shift < _SILENT_DRIFT_THRESHOLD else "DRIFT — emitting event",
)
if shift < _SILENT_DRIFT_THRESHOLD:
return
try:
Expand Down
31 changes: 25 additions & 6 deletions tests/test_daemon.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -775,21 +775,26 @@ def test_usage_anchor_drift_measured_on_reanchor(tmp_path, monkeypatch):
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
def test_silent_provider_drift_emits_event(tmp_path, monkeypatch, caplog):
"""Issue #1027 — heinrichneb (Dev.to 3dicj): a provider silently changing
under an unchanged base_url/model alias keeps the old provider's real
prompt_tokens as the projection base — the anchor "looks healthy while it
drifts". A fresh real_pt whose bias (real/est) deviates from the previous
anchored round beyond the threshold must emit a countable
anchor_provider_drift event and re-anchor on the new real number."""
anchor_provider_drift event and re-anchor on the new real number.

Issue #1072 (Dev.to 3dlo4) — planted-fire measurable: the unconditional
bias-shift heartbeat (grep "anchor-bias-heartbeat") must appear in the
log even when drift fires, proving the detector ran this round."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "silent-drift"
# Provider A round: real 222K vs est 148K → bias 1.5 (the #946 shape)
server._usage_anchors[sid] = (222_000, 148_000)
# Provider B round (same base_url): real 360K vs est 150K → bias 2.4
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 360_000, 150_000)

lines = stats.read_text(encoding="utf-8").strip().splitlines()
assert len(lines) == 1
Expand All@@ -800,29 +805,43 @@ def test_silent_provider_drift_emits_event(tmp_path, monkeypatch):
assert ev["prev_est"] == 148_000 and ev["estimate"] == 150_000
assert ev["bias_shift"] == pytest.approx(0.6, abs=0.01) # (2.4-1.5)/1.5
assert ev["model"] == "gpt-4o-mini" and ev["provider"] == "localhost"
# Heartbeat (issue #1072): unconditional shift log present + DRIFT flag
assert "anchor-bias-heartbeat session=silent-drift" in caplog.text
assert "bias_shift=0.6000" in caplog.text
assert "DRIFT — emitting event" in caplog.text
assert "usage anchor silent drift session=silent-drift" in caplog.text
# Re-anchor on the new provider's real number (natural anchor overwrite)
server._usage_anchors[sid] = (360_000, 150_000)
# Same provider bias again → no second event (stable after re-anchor)
server._detect_silent_anchor_drift(_SidSession(sid), 365_000, 152_000)
assert len(stats.read_text(encoding="utf-8").strip().splitlines()) == 1


def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch):
def test_silent_drift_below_threshold_silent(tmp_path, monkeypatch, caplog):
"""Issue #1027 — a small per-round bias wobble (same provider, estimate
noise) must NOT emit a drift event: the threshold separates real
tokenizer changes from normal variance."""
tokenizer changes from normal variance. Issue #1072 — the unconditional
heartbeat still proves the detector ran (no event, no warning)."""
stats = tmp_path / "usage-anchor.jsonl"
monkeypatch.setattr(daemon_mod, "_USAGE_ANCHOR_STATS_PATH", stats)
server = _make_server()
sid = "no-drift"
server._usage_anchors[sid] = (222_000, 148_000) # bias 1.5
# Same provider: real 240K vs est 150K → bias 1.6 → shift 6.7% < 25%
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
with caplog.at_level("DEBUG", logger="emrg.server.daemon"):
server._detect_silent_anchor_drift(_SidSession(sid), 240_000, 150_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
# Heartbeat present with "within threshold" verdict; no drift warning
assert "anchor-bias-heartbeat session=no-drift" in caplog.text
assert "bias_shift=0.0667" in caplog.text
assert "within threshold, no drift" in caplog.text
assert "usage anchor silent drift" not in caplog.text

# No anchor at all → no-op (first round, nothing to compare against)
caplog.clear()
server._detect_silent_anchor_drift(_SidSession("fresh"), 10_000, 9_000)
assert not stats.exists() or stats.read_text(encoding="utf-8").strip() == ""
assert "anchor-bias-heartbeat" not in caplog.text # no old anchor → skip


def test_usage_anchor_cross_provider_window_attributable(tmp_path, monkeypatch):
Expand Down
Loading