mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-25 09:20:53 +08:00
Merge pull request #499 from NikolayGusev-astra/fix/telemetry-on-and-registration-gap
fix: context telemetry ON by default + counter for proved-but-unregistered intents
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 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(dataEnvelope) 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
+42
-1
@@ -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(dataEnvelope) string
|
||||
}
|
||||
|
||||
func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {
|
||||
@@ -402,13 +406,50 @@ 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(env dataEnvelope) string { return factOnlyBlock(ts, env) },
|
||||
}
|
||||
}
|
||||
|
||||
// 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, env dataEnvelope) string {
|
||||
if ts == nil {
|
||||
return ""
|
||||
}
|
||||
rows, err := ts.FactOnlyIntents(0)
|
||||
if err != nil || len(rows) == 0 {
|
||||
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: 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()
|
||||
}
|
||||
|
||||
// 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(env)
|
||||
}
|
||||
return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block
|
||||
}
|
||||
|
||||
// plannerDefaultTmpl is the built-in EDITABLE body (section [A]) of the planner
|
||||
|
||||
@@ -1211,6 +1211,60 @@ 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 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
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
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 {
|
||||
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)
|
||||
|
||||
// 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)
|
||||
}
|
||||
if err := store.Link(intentA, RelYields, factA); err != nil {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
_ = 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")
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -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"`
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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. 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 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
|
||||
|
||||
@@ -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 env unset")
|
||||
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 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")
|
||||
|
||||
+1
-1
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user