From b708ea6b9a9124fab38c4b2ea9358620ba9736a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=93=D1=83?= =?UTF-8?q?=D1=81=D0=B5=D0=B2?= Date: Mon, 23 Nov 2026 01:32:07 +0300 Subject: [PATCH 1/3] fix(llmrec): context size telemetry ON by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The llm_context table carries the per-call context breakdown (system, tools, tool_result, assistant) but was EMPTY on a stand that had already run 15 tasks: the flag was opt-in and off. Context size was therefore discussed from per-task token sums, and any fix to it was a guess. limits: telemetry row 1 per model call - byte counting only, no content kept; наблюдаемо до ~300 вызовов на прогон, то есть до ~300 строк limits: disable via explicit falsy value only (0|false|off|no) - the point of the change is that an unset env means ON Tests: default-on and explicit-off are both asserted (RED first: the old test asserted the opposite default). --- llmrec/context_telemetry.go | 21 +++++++++++++-------- llmrec/context_telemetry_test.go | 16 +++++++++++++--- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/llmrec/context_telemetry.go b/llmrec/context_telemetry.go index 92b1fbd86..1d067d02d 100644 --- a/llmrec/context_telemetry.go +++ b/llmrec/context_telemetry.go @@ -10,19 +10,24 @@ import ( "github.com/Autumn-27/norma/llm" ) -// ContextTelemetryEnv is the opt-in environment flag enabling per-call context -// size telemetry into llm_context. Off by default: when unset/false, no sizing -// work runs and no rows are written. +// ContextTelemetryEnv switches per-call context size telemetry into llm_context. +// +// ON by default. Замер: на стенде, где прошло 15 прогонов, таблица llm_context была +// ПУСТА (0 строк), потому что флаг выключен по умолчанию — то есть размер контекста +// воркера обсуждали по суммарным токенам задачи, а не по разбивке (2026-11-22). +// Стоимость: одна строка на вызов модели и подсчёт длин, содержимое не сохраняется +// (по логам стенда — до ~300 вызовов на прогон, то есть до ~300 строк). +// Выключение явное: ARTEX_CONTEXT_TELEMETRY=0|false|off|no. const ContextTelemetryEnv = "ARTEX_CONTEXT_TELEMETRY" -// ContextTelemetryEnabled reports whether ARTEX_CONTEXT_TELEMETRY is enabled -// (1, true, on, yes; case-insensitive). Default is false. +// ContextTelemetryEnabled reports whether context telemetry is on. Default true; +// only an explicit falsy value (0, false, off, no; case-insensitive) turns it off. func ContextTelemetryEnabled() bool { switch strings.ToLower(strings.TrimSpace(os.Getenv(ContextTelemetryEnv))) { - case "1", "true", "on", "yes": - return true + case "0", "false", "off", "no": + return false } - return false + return true } // ContextMetrics holds size-only measurements of an assembled CompletionRequest diff --git a/llmrec/context_telemetry_test.go b/llmrec/context_telemetry_test.go index c3b512942..85a651b5f 100644 --- a/llmrec/context_telemetry_test.go +++ b/llmrec/context_telemetry_test.go @@ -233,11 +233,21 @@ func TestContextTelemetryFlagOffAndOnPostgres(t *testing.T) { wantMetrics := MeasureContext(req) wantUsage := llm.Usage{InputTokens: 1200, OutputTokens: 150, CacheReadTokens: 800, CacheWriteTokens: 100} - // 1. Flag OFF (default): zero rows in llm_context on both Stream and Complete, - // identical behavior regardless of recordBodies. + // 0. Default is ON: unset means enabled, only an explicit falsy value disables. t.Setenv(ContextTelemetryEnv, "") + if !ContextTelemetryEnabled() { + t.Fatal("expected telemetry enabled by default when env unset") + } + t.Setenv(ContextTelemetryEnv, "off") + if ContextTelemetryEnabled() { + t.Fatal("expected telemetry disabled when ARTEX_CONTEXT_TELEMETRY=off") + } + + // 1. Flag OFF explicitly: zero rows in llm_context on both Stream and Complete, + // identical behavior regardless of recordBodies. + t.Setenv(ContextTelemetryEnv, "0") if ContextTelemetryEnabled() { - t.Fatal("expected telemetry disabled when env unset") + t.Fatal("expected telemetry disabled when ARTEX_CONTEXT_TELEMETRY=0") } recOff := Wrap(syntheticTelemetryProvider{usage: wantUsage}, pg, "claude-test", "prof-a", "", "", func() bool { return false }) ctxOff := transcript.WithSessionID(WithTaskID(context.Background(), taskOff), "exp1-worker-i1") From 8e1c88e803f8136354ce71422a639b1496f9a75b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=93=D1=83?= =?UTF-8?q?=D1=81=D0=B5=D0=B2?= Date: Mon, 23 Nov 2026 01:32:07 +0300 Subject: [PATCH 2/3] fix(agent,db): counter for intents that proved facts and registered no finding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «Доказал — не зарегистрировал» was measurable all along and nobody measured it: on the 2026-11-22 run record, 3 runs out of 12 had EVERY fact-producing intent register nothing (3/3, 3/3, 2/2 intents) — task 8 burned 130 Bash calls in 35 minutes and registered zero findings. Facts carry no "this is a defect" flag, so the planner is the only place that can turn a fact into a finding; it had no counter telling it that a finished intent yielded facts and nothing else. db: FactOnlyIntents(limit) — intents with >=1 fact edge and no finding edge. agent: the situational block now carries them with the rule (register or say why not), so the nudge survives seeded agent_prompts (the block is code-owned, not a template). limits: FactOnlyIntents limit default 10 - a planner round acts on a handful, the counter is a nudge and not an inventory limits: summary truncation 140 chars - one-sentence intent summaries; full text stays one node_detail away, and the block must not become a second context source Tests RED first: db test asserts the fact-without-finding intent is picked and the fact+findings one is not; agent test asserts the block reaches the situational prompt and does not appear for an empty lookup. --- agent/fact_only_block_test.go | 25 +++++++++++ agent/planner.go | 39 +++++++++++++++- db/exploration.go | 53 ++++++++++++++++++++++ db/fact_only_intents_test.go | 83 +++++++++++++++++++++++++++++++++++ 4 files changed, 199 insertions(+), 1 deletion(-) create mode 100644 agent/fact_only_block_test.go create mode 100644 db/fact_only_intents_test.go diff --git a/agent/fact_only_block_test.go b/agent/fact_only_block_test.go new file mode 100644 index 000000000..297bfb565 --- /dev/null +++ b/agent/fact_only_block_test.go @@ -0,0 +1,25 @@ +package agent + +import ( + "strings" + "testing" +) + +// Блок «доказал — не зарегистрировал» обязан попадать в ситуационный блок планировщика: +// без него счётчик есть, а планировщик его не видит. Второй случай — тесты и вызовы без +// factOnly (nil) не должны падать и не должны печатать блок. +func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) { + with := plannerSituational(nil, triggerLookup{ + factOnly: func() string { + return "\n\n[Proved but not registered: 2 finished intent(s) produced facts and NO finding.]\n" + }, + }, nil, newDataEnvelope()) + if !strings.Contains(with, "Proved but not registered") { + t.Fatalf("situational block lost the fact-only nudge:\n%s", with) + } + + without := plannerSituational(nil, triggerLookup{}, nil, newDataEnvelope()) + if strings.Contains(without, "Proved but not registered") { + t.Fatalf("empty lookup should not print the block:\n%s", without) + } +} diff --git a/agent/planner.go b/agent/planner.go index 708756bc3..99ed17222 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "strconv" "strings" "sync" @@ -395,6 +396,9 @@ type triggerLookup struct { intentSummary func(int64) string workerOutput func(int64) string factIDs func(int64) string + // factOnly renders the «proved but not registered» block: intents that produced + // facts and no finding. Nil in tests that do not care about it. + factOnly func() string } func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup { @@ -402,13 +406,46 @@ func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup { intentSummary: func(id int64) string { return intentSummary(ts, id) }, workerOutput: func(id int64) string { return workerOutput(ts, id) }, factIDs: func(id int64) string { return factIDsYielded(ts, id) }, + factOnly: func() string { return factOnlyBlock(ts) }, } } +// factOnlyBlock names the intents whose work proved something and registered no +// finding — the defect the run record shows plainly (three runs in twelve had every +// fact-producing intent register nothing). A fact carries no "this is a defect" +// flag, so the planner is the only place that can turn one into a finding; without +// the counter it has to notice by reading every fact again. +func factOnlyBlock(ts *db.ExplorationStore) string { + if ts == nil { + return "" + } + rows, err := ts.FactOnlyIntents(0) + if err != nil || len(rows) == 0 { + return "" + } + var b strings.Builder + b.WriteString("\n\n[Proved but not registered: ") + b.WriteString(strconv.Itoa(len(rows))) + b.WriteString(" finished intent(s) produced facts and NO finding. For each, decide explicitly: " + + "either register the defect as a finding (report_finding, with the executed request as evidence) " + + "or state why the fact is not a defect. Facts carry no defect flag — only you can turn one into a finding.]\n") + for _, r := range rows { + // 140: сводка интента — одно предложение; 140 символов хватает, чтобы отличить + // направления друг от друга (полный текст в одной node_detail). Обрезка общая + // с триггерами, чтобы блок не стал вторым источником контекста. + b.WriteString(fmt.Sprintf(" #%d (%d fact(s)): %s\n", r.IntentID, r.Facts, truncOutput(r.Summary, 140))) + } + return b.String() +} + // plannerSituational is the planner's situational block for one round: the // envelope intro, the triggers, then the overview, all framed with env. func plannerSituational(evs []TriggerEvent, look triggerLookup, data map[string]any, env dataEnvelope) string { - return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block := "" + if look.factOnly != nil { + block = look.factOnly() + } + return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block } // plannerDefaultTmpl is the built-in EDITABLE body (section [A]) of the planner diff --git a/db/exploration.go b/db/exploration.go index aa63910ce..662c83d87 100644 --- a/db/exploration.go +++ b/db/exploration.go @@ -1211,6 +1211,59 @@ WHERE e.exploration_id=$1 AND e.rel=$2 AND n.kind='finding'`, s.expID, RelYields return out, rows.Err() } +// FactOnlyIntent is one intent that yielded facts and no finding — the measurable +// form of «proved but not registered». +type FactOnlyIntent struct { + IntentID int64 + Summary string + Facts int +} + +// FactOnlyIntents returns the intents of this exploration that yielded at least one +// fact node and zero finding nodes, newest first, capped at limit. +// +// Why it exists: on the run record, three runs out of twelve had EVERY +// fact-producing intent register nothing (3/3, 3/3, 2/2 — llm/agent logs of the +// 2026-11-22 stand). Facts were proven, findings never reached the registry, and +// nothing in the graph connected the two, so the planner could not notice. +// The counter is deliberately about the intent, not the fact: a fact carries no +// "this is a defect" flag, while an intent that produced facts has finished work +// whose result the planner can judge. +// +// limit<=0 falls back to 10: a planner round acts on a handful, and the whole +// point is a nudge, not an inventory. +func (s *ExplorationStore) FactOnlyIntents(limit int) ([]FactOnlyIntent, error) { + if limit <= 0 { + limit = 10 + } + rows, err := s.db.Query(`SELECT i.id, COALESCE(i.payload->>'summary',''), count(*) +FROM exploration_edges e +JOIN exploration_nodes i ON i.id=e.src_id AND i.exploration_id=e.exploration_id +JOIN exploration_nodes d ON d.id=e.dst_id AND d.exploration_id=e.exploration_id +WHERE e.exploration_id=$1 AND e.rel=$2 AND d.kind=$3 + AND NOT EXISTS ( + SELECT 1 FROM exploration_edges e2 + JOIN exploration_nodes f ON f.id=e2.dst_id AND f.exploration_id=e2.exploration_id + WHERE e2.exploration_id=e.exploration_id AND e2.src_id=e.src_id + AND e2.rel=$2 AND f.kind='finding') +GROUP BY i.id, 2 +ORDER BY i.id DESC +LIMIT $4`, s.expID, RelYields, KindFact, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []FactOnlyIntent + for rows.Next() { + var r FactOnlyIntent + if err := rows.Scan(&r.IntentID, &r.Summary, &r.Facts); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + // FindingIntentsTerminal is the inherited-history variant: it returns finding // lineage only when the producing intent has reached an immutable terminal // state. This keeps a source task's live worker topology private. diff --git a/db/fact_only_intents_test.go b/db/fact_only_intents_test.go new file mode 100644 index 000000000..c0c65520e --- /dev/null +++ b/db/fact_only_intents_test.go @@ -0,0 +1,83 @@ +package db + +import "testing" + +// «Доказал — не зарегистрировал» в измеримой форме: интент, который дал факты и не +// дал ни одной находки. Тест держит оба случая сразу, иначе гейт зелёный на пустом +// множестве: интент А (факт, находки нет) должен попасть, интент Б (факт + находка) — нет. +func TestFactOnlyIntents(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + t.Cleanup(func() { d.Close() }) + + expID, err := d.CreateExploration("fact only intents", "fact only intents") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) }) + store := d.Exploration(expID) + + // А: факт есть, находки нет — «доказал, не зарегистрировал». + intentA, err := store.AddIntent(map[string]any{"summary": "proved X, never registered"}, 1, nil, "planner") + if err != nil { + t.Fatal(err) + } + factA, err := store.AddNode(KindFact, map[string]any{"summary": "X is injectable"}, 1, "confirmed", "worker", nil) + if err != nil { + t.Fatal(err) + } + if err := store.Link(intentA, RelYields, factA); err != nil { + t.Fatal(err) + } + + // Б: факт и находка — не должен попасть. + intentB, err := store.AddIntent(map[string]any{"summary": "proved Y and registered"}, 1, nil, "planner") + if err != nil { + t.Fatal(err) + } + factB, err := store.AddNode(KindFact, map[string]any{"summary": "Y is injectable"}, 1, "confirmed", "worker", nil) + if err != nil { + t.Fatal(err) + } + findingB, err := store.AddNode(KindFinding, map[string]any{"summary": "Y finding"}, 1, "confirmed", "worker", nil) + if err != nil { + t.Fatal(err) + } + if err := store.Link(intentB, RelYields, factB); err != nil { + t.Fatal(err) + } + if err := store.Link(intentB, RelYields, findingB); err != nil { + t.Fatal(err) + } + + // В: интент вообще без фактов — тоже не должен попасть. + intentC, err := store.AddIntent(map[string]any{"summary": "nothing yet"}, 1, nil, "planner") + if err != nil { + t.Fatal(err) + } + _ = intentC + + got, err := store.FactOnlyIntents(10) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 { + t.Fatalf("FactOnlyIntents returned %d intents, want 1 (only the fact-without-finding one): %+v", len(got), got) + } + if got[0].IntentID != intentA { + t.Fatalf("FactOnlyIntents picked intent %d, want %d", got[0].IntentID, intentA) + } + if got[0].Facts != 1 { + t.Fatalf("FactOnlyIntents facts = %d, want 1", got[0].Facts) + } + if got[0].Summary == "" { + t.Fatal("FactOnlyIntents lost the intent summary — the planner cannot act on an id alone") + } + + // Порог по умолчанию: limit<=0 не должен возвращать пусто. + if many, err := store.FactOnlyIntents(0); err != nil || len(many) != 1 { + t.Fatalf("FactOnlyIntents(0) = (%d, %v), want 1 row via the default cap", len(many), err) + } +} From deba1d1c7a11b3ede91c9364c9eaba7b68710cc1 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:12:41 +0100 Subject: [PATCH 3/3] fix(agent,db): finish the fact-only counter FactOnlyIntents now returns only terminal intents (done, blocked, exhausted, stopped), so an open, running or deleted intent is no longer reported as finished. The summaries go into the planner block inside env.wrap, and the telemetry docs, the llmrec comment and the db comment match the on-by-default flag with 0|false|off|no to disable it. --- agent/fact_only_block_test.go | 22 +++++++++-- agent/planner.go | 22 ++++++----- db/exploration.go | 1 + db/fact_only_intents_test.go | 71 +++++++++++++++++++++++++++++++---- db/llm_context.go | 5 ++- docs/context-telemetry.md | 8 ++-- llmrec/context_telemetry.go | 12 +++--- llmrec/llmrec.go | 2 +- 8 files changed, 110 insertions(+), 33 deletions(-) diff --git a/agent/fact_only_block_test.go b/agent/fact_only_block_test.go index 297bfb565..101f54769 100644 --- a/agent/fact_only_block_test.go +++ b/agent/fact_only_block_test.go @@ -5,12 +5,12 @@ import ( "testing" ) -// Блок «доказал — не зарегистрировал» обязан попадать в ситуационный блок планировщика: -// без него счётчик есть, а планировщик его не видит. Второй случай — тесты и вызовы без -// factOnly (nil) не должны падать и не должны печатать блок. +// The «proved but not registered» block must reach the planner's situational block. +// Without it the counter exists and the planner never sees it. Calls without a +// lookup (nil factOnly) must not panic and must not print the block. func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) { with := plannerSituational(nil, triggerLookup{ - factOnly: func() string { + factOnly: func(dataEnvelope) string { return "\n\n[Proved but not registered: 2 finished intent(s) produced facts and NO finding.]\n" }, }, nil, newDataEnvelope()) @@ -23,3 +23,17 @@ func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) { t.Fatalf("empty lookup should not print the block:\n%s", without) } } + +// The lookup receives the round's envelope, so the block can frame its data with it. +func TestFactOnlyLookupReceivesRoundEnvelope(t *testing.T) { + env := newDataEnvelope() + var got dataEnvelope + look := triggerLookup{factOnly: func(e dataEnvelope) string { + got = e + return "" + }} + _ = plannerSituational(nil, look, nil, env) + if got.nonce != env.nonce { + t.Fatalf("lookup got nonce %q, want the round nonce %q", got.nonce, env.nonce) + } +} diff --git a/agent/planner.go b/agent/planner.go index 99ed17222..5c6e4bfb0 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -398,7 +398,7 @@ type triggerLookup struct { factIDs func(int64) string // factOnly renders the «proved but not registered» block: intents that produced // facts and no finding. Nil in tests that do not care about it. - factOnly func() string + factOnly func(dataEnvelope) string } func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup { @@ -406,7 +406,7 @@ func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup { intentSummary: func(id int64) string { return intentSummary(ts, id) }, workerOutput: func(id int64) string { return workerOutput(ts, id) }, factIDs: func(id int64) string { return factIDsYielded(ts, id) }, - factOnly: func() string { return factOnlyBlock(ts) }, + factOnly: func(env dataEnvelope) string { return factOnlyBlock(ts, env) }, } } @@ -415,7 +415,7 @@ func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup { // fact-producing intent register nothing). A fact carries no "this is a defect" // flag, so the planner is the only place that can turn one into a finding; without // the counter it has to notice by reading every fact again. -func factOnlyBlock(ts *db.ExplorationStore) string { +func factOnlyBlock(ts *db.ExplorationStore, env dataEnvelope) string { if ts == nil { return "" } @@ -424,17 +424,21 @@ func factOnlyBlock(ts *db.ExplorationStore) string { return "" } var b strings.Builder + var list strings.Builder b.WriteString("\n\n[Proved but not registered: ") b.WriteString(strconv.Itoa(len(rows))) b.WriteString(" finished intent(s) produced facts and NO finding. For each, decide explicitly: " + "either register the defect as a finding (report_finding, with the executed request as evidence) " + "or state why the fact is not a defect. Facts carry no defect flag — only you can turn one into a finding.]\n") for _, r := range rows { - // 140: сводка интента — одно предложение; 140 символов хватает, чтобы отличить - // направления друг от друга (полный текст в одной node_detail). Обрезка общая - // с триггерами, чтобы блок не стал вторым источником контекста. - b.WriteString(fmt.Sprintf(" #%d (%d fact(s)): %s\n", r.IntentID, r.Facts, truncOutput(r.Summary, 140))) - } + // 140: one sentence of intent summary; 140 characters is enough to tell the + // directions apart (the full text is in one node_detail). The cut is shared + // with the triggers so the block does not become a second context source. + fmt.Fprintf(&list, " #%d (%d fact(s)): %s\n", r.IntentID, r.Facts, truncOutput(r.Summary, 140)) + } + // The summaries come from agent output: they are data and go inside the envelope. + b.WriteString(env.wrap("fact_only_intents", strings.TrimRight(list.String(), "\n"))) + b.WriteString("\n") return b.String() } @@ -443,7 +447,7 @@ func factOnlyBlock(ts *db.ExplorationStore) string { func plannerSituational(evs []TriggerEvent, look triggerLookup, data map[string]any, env dataEnvelope) string { block := "" if look.factOnly != nil { - block = look.factOnly() + block = look.factOnly(env) } return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block } diff --git a/db/exploration.go b/db/exploration.go index 662c83d87..688f39f61 100644 --- a/db/exploration.go +++ b/db/exploration.go @@ -1241,6 +1241,7 @@ FROM exploration_edges e JOIN exploration_nodes i ON i.id=e.src_id AND i.exploration_id=e.exploration_id JOIN exploration_nodes d ON d.id=e.dst_id AND d.exploration_id=e.exploration_id WHERE e.exploration_id=$1 AND e.rel=$2 AND d.kind=$3 + AND i.state IN ('done','blocked','exhausted','stopped') AND NOT EXISTS ( SELECT 1 FROM exploration_edges e2 JOIN exploration_nodes f ON f.id=e2.dst_id AND f.exploration_id=e2.exploration_id diff --git a/db/fact_only_intents_test.go b/db/fact_only_intents_test.go index c0c65520e..66f938fef 100644 --- a/db/fact_only_intents_test.go +++ b/db/fact_only_intents_test.go @@ -2,9 +2,10 @@ package db import "testing" -// «Доказал — не зарегистрировал» в измеримой форме: интент, который дал факты и не -// дал ни одной находки. Тест держит оба случая сразу, иначе гейт зелёный на пустом -// множестве: интент А (факт, находки нет) должен попасть, интент Б (факт + находка) — нет. +// "Proved but not registered", in measurable form: an intent that yielded facts and +// no finding. The test holds both cases at once, otherwise the gate is green on an +// empty set: intent A (fact, no finding) must be returned, intent B (fact + finding) +// must not. func TestFactOnlyIntents(t *testing.T) { d, err := Open(testDSN(t)) if err != nil { @@ -19,11 +20,15 @@ func TestFactOnlyIntents(t *testing.T) { t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) }) store := d.Exploration(expID) - // А: факт есть, находки нет — «доказал, не зарегистрировал». + // A: fact present, no finding — "proved, not registered". intentA, err := store.AddIntent(map[string]any{"summary": "proved X, never registered"}, 1, nil, "planner") if err != nil { t.Fatal(err) } + // Only finished intents count: the state filter keeps A (done) and drops open ones. + if err := store.SetIntentState(intentA, "done"); err != nil { + t.Fatal(err) + } factA, err := store.AddNode(KindFact, map[string]any{"summary": "X is injectable"}, 1, "confirmed", "worker", nil) if err != nil { t.Fatal(err) @@ -32,7 +37,7 @@ func TestFactOnlyIntents(t *testing.T) { t.Fatal(err) } - // Б: факт и находка — не должен попасть. + // B: fact and finding — must not be returned. intentB, err := store.AddIntent(map[string]any{"summary": "proved Y and registered"}, 1, nil, "planner") if err != nil { t.Fatal(err) @@ -52,7 +57,7 @@ func TestFactOnlyIntents(t *testing.T) { t.Fatal(err) } - // В: интент вообще без фактов — тоже не должен попасть. + // C: intent with no facts at all — must not be returned either. intentC, err := store.AddIntent(map[string]any{"summary": "nothing yet"}, 1, nil, "planner") if err != nil { t.Fatal(err) @@ -76,8 +81,60 @@ func TestFactOnlyIntents(t *testing.T) { t.Fatal("FactOnlyIntents lost the intent summary — the planner cannot act on an id alone") } - // Порог по умолчанию: limit<=0 не должен возвращать пусто. + // Default cap: limit<=0 must not return nothing. if many, err := store.FactOnlyIntents(0); err != nil || len(many) != 1 { t.Fatalf("FactOnlyIntents(0) = (%d, %v), want 1 row via the default cap", len(many), err) } } + +// Only finished intents (done, blocked, exhausted, stopped) count. An intent that is +// still open or running with a fact and no finding must not be reported as finished. +func TestFactOnlyIntentsStates(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + t.Cleanup(func() { d.Close() }) + + expID, err := d.CreateExploration("fact only states", "fact only states") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) }) + store := d.Exploration(expID) + + states := []string{"open", "running", "done", "blocked", "exhausted", "stopped"} + want := map[int64]bool{} + for _, st := range states { + id, err := store.AddIntent(map[string]any{"summary": "state " + st}, 1, nil, "planner") + if err != nil { + t.Fatal(err) + } + if err := store.SetIntentState(id, st); err != nil { + t.Fatal(err) + } + fact, err := store.AddNode(KindFact, map[string]any{"summary": "fact for " + st}, 1, "confirmed", "worker", nil) + if err != nil { + t.Fatal(err) + } + if err := store.Link(id, RelYields, fact); err != nil { + t.Fatal(err) + } + if st == "done" || st == "blocked" || st == "exhausted" || st == "stopped" { + want[id] = true + } + } + + got, err := store.FactOnlyIntents(0) + if err != nil { + t.Fatal(err) + } + if len(got) != len(want) { + t.Fatalf("FactOnlyIntents returned %d intents, want %d (terminal states only): %+v", len(got), len(want), got) + } + for _, g := range got { + if !want[g.IntentID] { + t.Fatalf("FactOnlyIntents returned intent %d in a non-terminal state", g.IntentID) + } + } +} diff --git a/db/llm_context.go b/db/llm_context.go index ce4951d23..7b1fedea1 100644 --- a/db/llm_context.go +++ b/db/llm_context.go @@ -5,8 +5,9 @@ import ( "strings" ) -// LLMContext is one opt-in context-size telemetry row written when -// ARTEX_CONTEXT_TELEMETRY=1. It records only byte sizes, counts, token usage, +// LLMContext is one context-size telemetry row, written on every model call while +// telemetry is on (the default; ARTEX_CONTEXT_TELEMETRY=0|false|off|no turns it off). +// It records only byte sizes, counts, token usage, // and call metadata — never any prompt, tool, or message content. type LLMContext struct { TaskID string `json:"task_id"` diff --git a/docs/context-telemetry.md b/docs/context-telemetry.md index 6d8f2e3b2..86974e58d 100644 --- a/docs/context-telemetry.md +++ b/docs/context-telemetry.md @@ -1,6 +1,6 @@ # LLM Context Size Telemetry (P3.5 Phase A) -`ARTEX_CONTEXT_TELEMETRY=1` enables opt-in, size-only per-call telemetry for every `llmrec` `Stream` and `Complete` call. It is **disabled by default**: when off, no request sizing runs and no rows are written to PostgreSQL. +Size-only per-call telemetry runs for every `llmrec` `Stream` and `Complete` call. It is **on by default**; `ARTEX_CONTEXT_TELEMETRY=0|false|off|no` disables it explicitly, and then no request sizing runs and no rows are written to PostgreSQL. This phase measures context composition without changing any prompt, compaction policy, or model behavior, so Phases B (`ARTEX_BOUNDED_CONTEXT`) and C (`ARTEX_CACHE_PREFIX` / `ARTEX_COMPACTION_MEMO`) can be evaluated against real numbers first. @@ -10,13 +10,13 @@ This phase measures context composition without changing any prompt, compaction | Environment variable | Values | Default | |---|---|---| -| `ARTEX_CONTEXT_TELEMETRY` | `1`, `true`, `on`, `yes` (case-insensitive) | off | +| `ARTEX_CONTEXT_TELEMETRY` | `0`, `false`, `off`, `no` disable it (case-insensitive); anything else, or unset, keeps it on | on | -Telemetry runs independently of `llm_record` (`recordBodies`): enabling `ARTEX_CONTEXT_TELEMETRY=1` works even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata. +Telemetry runs independently of `llm_record` (`recordBodies`): it stays on even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata. ### Stopping, retention, and write cost -When `ARTEX_CONTEXT_TELEMETRY=1` is active, each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Unset `ARTEX_CONTEXT_TELEMETRY` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically: +While telemetry is on (the default), each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Set `ARTEX_CONTEXT_TELEMETRY=0` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically: ```sql DELETE FROM llm_context WHERE ts < now() - interval '30 days'; diff --git a/llmrec/context_telemetry.go b/llmrec/context_telemetry.go index 1d067d02d..edfc1acf6 100644 --- a/llmrec/context_telemetry.go +++ b/llmrec/context_telemetry.go @@ -12,12 +12,12 @@ import ( // ContextTelemetryEnv switches per-call context size telemetry into llm_context. // -// ON by default. Замер: на стенде, где прошло 15 прогонов, таблица llm_context была -// ПУСТА (0 строк), потому что флаг выключен по умолчанию — то есть размер контекста -// воркера обсуждали по суммарным токенам задачи, а не по разбивке (2026-11-22). -// Стоимость: одна строка на вызов модели и подсчёт длин, содержимое не сохраняется -// (по логам стенда — до ~300 вызовов на прогон, то есть до ~300 строк). -// Выключение явное: ARTEX_CONTEXT_TELEMETRY=0|false|off|no. +// ON by default. Measurement: on the test bench, 15 runs left llm_context EMPTY +// (0 rows) because the flag was off by default, so the worker's context size was +// discussed from the task's total tokens, not from a breakdown (2026-11-22). +// Cost: one row per model call plus length counts; no content is stored (up to about +// 300 calls per run in the bench logs, so up to about 300 rows). +// Explicit off switch: ARTEX_CONTEXT_TELEMETRY=0|false|off|no. const ContextTelemetryEnv = "ARTEX_CONTEXT_TELEMETRY" // ContextTelemetryEnabled reports whether context telemetry is on. Default true; diff --git a/llmrec/llmrec.go b/llmrec/llmrec.go index 8d15f8c31..0eb75da11 100644 --- a/llmrec/llmrec.go +++ b/llmrec/llmrec.go @@ -211,7 +211,7 @@ func (r *Recorder) Stream(ctx context.Context, req llm.CompletionRequest) iter.S } // Lightweight metering row — always written. r.recordUsage(ctx, taskID, expID, worker, usage, int(time.Since(start).Milliseconds()), status) - // Opt-in context size telemetry — independent of recordBodies. + // Context size telemetry (on by default) — independent of recordBodies. if collectContext { r.recordContext(taskID, worker, ctxMetrics, usage, status) }