Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

llmrec: decide usage status when the consumer stops reading

Adam Rufaro Dzitiro2db355389a9e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46638aa..53c0c1e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
+- **LLM usage status on early stream exit**: when a consumer stops reading a stream before `message_stop`, the recorder now stores the `llm_usage` row as `error` at that point, whether or not the context was cancelled, instead of inferring the status from `ctx.Err()` in a deferred call. `TestSideUsageRecordedOnceOnConsumerCancellation` runs again (follow-up to #9).
- **Workspace and skill symlink confinement**: workspace file operations, the skill file APIs and the skill loader resolve symlinks in every path component and refuse a target outside their root, so a link planted in the workspace or a skill directory cannot expose another file.
- **Target gate behind proxies**: a target approval is name-only whenever a proxy is in the path, including the recording proxy, the global egress proxy and a custom tool's own proxy, so the gate never claims an IP binding the proxy does not enforce.
- **Remote MCP response bound**: Streamable HTTP JSON-RPC bodies and SSE data payloads are refused above 8 MiB, so a remote MCP server cannot force an unbounded decode.
diff --git a/llmrec/llmrec.go b/llmrec/llmrec.go
index 05dd1bc..9743577 100644
--- a/llmrec/llmrec.go
+++ b/llmrec/llmrec.go
@@ -6,6 +6,7 @@ package llmrec
import (
"context"
"encoding/json"
+ "errors"
"iter"
"log"
"strings"
@@ -16,6 +17,11 @@ import (
"github.com/Autumn-27/norma/transcript"
)
+// errStreamAbandoned marks a stream whose consumer stopped reading before
+// message_stop while its context was still live. The call did not complete,
+// so it is metered as an error rather than inferred from ctx.Err().
+var errStreamAbandoned = errors.New("llmrec: consumer stopped reading before message_stop")
+
type taskIDContextKey struct{}
type workerContextKey struct{}
@@ -184,6 +190,7 @@ func (r *Recorder) Stream(ctx context.Context, req llm.CompletionRequest) iter.S
usage llm.Usage
stopReason string
streamErr error
+ complete bool // message_stop was seen
)
finished := false
@@ -236,8 +243,21 @@ func (r *Recorder) Stream(ctx context.Context, req llm.CompletionRequest) iter.S
stopReason = ev.StopReason
}
usage.MergeEcho(ev.Usage)
+ case llm.SEMessageStop:
+ complete = true
}
if !yield(ev, err) {
+ // The consumer stopped early. Decide the status here from what
+ // is known, not later in the deferred finish: the call only
+ // counts as "ok" if message_stop arrived and ctx is live.
+ switch {
+ case ctx.Err() != nil:
+ finish(ctx.Err())
+ case !complete:
+ finish(errStreamAbandoned)
+ default:
+ finish(nil)
+ }
return
}
}
diff --git a/llmrec/llmrec_test.go b/llmrec/llmrec_test.go
index 497d79c..c9e0987 100644
--- a/llmrec/llmrec_test.go
+++ b/llmrec/llmrec_test.go
@@ -151,15 +151,9 @@ func (meteredStreamProvider) Stream(context.Context, llm.CompletionRequest) iter
}
func TestSideUsageRecordedOnceOnConsumerCancellation(t *testing.T) {
- // Timing-sensitive on 2-core CI runners (BaaRai/ARTEX#9). Repro:
- // ARTEX_PG_DSN=postgres://artex:testpass@localhost:5432/artextest_race \
- // go test ./llmrec -run TestSideUsageRecordedOnceOnConsumerCancellation -count=20 -race -v
- // The `early=` t.Fatalf assertion below compares the single llm_usage row's
- // count/input/output/worker/status; in the `early` branch the status
- // occasionally comes back "ok" instead of "error" because the consumer's
- // cancellation and the recorder's deferred finish race on a loaded runner.
- // Keep the skip until the metering status is made cancellation-explicit.
- t.Skip("timing-sensitive on CI runners; repro and failing assertion documented above; BaaRai/ARTEX#9")
+ // Previously skipped as timing-sensitive (BaaRai/ARTEX#9). The recorder now
+ // decides the status at the point the consumer stops, so the result no
+ // longer depends on when the deferred finish runs.
dsn := os.Getenv("ARTEX_PG_DSN")
if dsn == "" {
t.Skip("requires isolated ARTEX_PG_DSN")
@@ -169,7 +163,9 @@ func TestSideUsageRecordedOnceOnConsumerCancellation(t *testing.T) {
t.Fatal(err)
}
defer pg.Close()
- for _, early := range []bool{false, true} {
+ // full: read to the end. cancel: cancel ctx, then stop reading.
+ // abandon: stop reading before message_stop with ctx still live.
+ for _, mode := range []string{"full", "cancel", "abandon"} {
profile := "btw-metering-" + uuid.NewString()
ctx, cancel := context.WithCancel(transcript.WithSessionID(t.Context(), "exp0-btw-test"))
recorder := Wrap(meteredStreamProvider{}, pg, "fixture", profile, "", "", func() bool { return false })
@@ -177,8 +173,10 @@ func TestSideUsageRecordedOnceOnConsumerCancellation(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if early && event.Type == llm.SEMessageDelta {
- cancel()
+ if mode != "full" && event.Type == llm.SEMessageDelta {
+ if mode == "cancel" {
+ cancel()
+ }
break // Consumer exits before the provider can return a cancellation event.
}
}
@@ -192,11 +190,11 @@ FROM llm_usage WHERE profile_name=$1`, profile).Scan(&count, &input, &output, &w
t.Fatal(err)
}
wantStatus := "ok"
- if early {
+ if mode != "full" {
wantStatus = "error"
}
if count != 1 || input != 23 || output != 5 || worker != "btw" || status != wantStatus {
- t.Fatalf("early=%v: count=%d usage=%d/%d worker=%q status=%q", early, count, input, output, worker, status)
+ t.Fatalf("mode=%s: count=%d usage=%d/%d worker=%q status=%q", mode, count, input, output, worker, status)
}
}
}