소스 검색

Observability: access log, correlation ids, metrics; Linux ops script

- One JSON access-log line per API response (request id, action, status,
  duration, tenant/principal; never bodies, queries or keys); ApiAccessLog
  setting turns it off
- A caller's X-Request-Id (8-64 safe chars) is kept for correlation
- GET /api/v1/metrics: Prometheus text with request counters and a latency
  histogram per action, plus memory/candidate/job/embedding/retrieval/feedback
  counts; needs AMK_METRICS_TOKEN (compose .env), 404 while unset
- scripts/ops.sh: migrate/provision/embed/backup/verify/restore on Linux
- AGENTS.md: the knowledge base lives on the production server; the local
  container is for tests only
- Tests: observability.sh (25); all eight suites pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/1/head
Daniel Covington 18 시간 전
부모
커밋
9c6158c08f
14개의 변경된 파일과 443개의 추가작업 그리고 4개의 파일을 삭제
  1. +3
    -0
      .gitignore
  2. +5
    -2
      AGENTS.md
  3. +4
    -1
      README.md
  4. +92
    -0
      app/controllers/ApiHealthController.asp
  5. +1
    -0
      core/autoload_core.asp
  6. +11
    -1
      core/lib.Api.asp
  7. +142
    -0
      core/lib.Observability.asp
  8. +1
    -0
      core/mvc.asp
  9. +2
    -0
      docker-compose.yml
  10. +1
    -0
      public/Default.asp
  11. +40
    -0
      public/api/memory-v1.openapi.json
  12. +2
    -0
      public/web.config
  13. +40
    -0
      scripts/ops.sh
  14. +99
    -0
      tests/observability.sh

+ 3
- 0
.gitignore 파일 보기

@@ -14,3 +14,6 @@

# Database backups (scripts/backup.cmd); keep copies somewhere else too
/db/backups/

# Compose variables (AMK_METRICS_TOKEN); local only
/.env

+ 5
- 2
AGENTS.md 파일 보기

@@ -40,16 +40,18 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w
- Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.sh`.
- Portability: `ApiPortabilityController` (`POST /exports`, `POST /imports`). The export format (`agent-memory-export`, `schema_version` 1) is a contract: a new canonical table or column means a new schema version (and an importer for the old one), and the import must keep ids, revisions, timestamps and principal ids, rebuild derived data (content hashes, FTS, `Emb_MarkPending`) and stay all-or-nothing. Regression suite: `bash tests/phase3-portability.sh`.
- Backup/restore: `scripts\backup.cmd backup|verify` and `scripts\restore.cmd <file>` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead.
- The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all seven suites (`tests/*.sh`).
- Observability: `core/lib.Observability.asp` (included before `lib.Api.asp`). `Api_Send` calls `Obs_Record` once per response (access-log line via `console.log`, counters in `Application`); `MVC_InvokeAction` sets `Obs_Action`, so metric labels are controller actions, never raw paths. A response written without `Api_Send` must call `Obs_Record status` itself (as `ApiHealthController.Metrics` does). Never log bodies, query strings or keys. `GET /api/v1/metrics` needs `AMK_METRICS_TOKEN` (`.env`, git-ignored). Regression suite: `bash tests/observability.sh`.
- The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all eight suites (`tests/*.sh`).

### This repo's own knowledge base (dogfooding)

The running API holds a tenant for this repo (`agent-memory-dev`, namespace `/projects/agent-memory`). Settings and keys are in `.amk.env` (git-ignored, local only; never print or commit the keys). Use `bash scripts/kb.sh` from Git Bash:
This repo's knowledge base lives on the **production server** (a separate VM running this app; its URL is `AMK_URL` in `.amk.env`), tenant for this repo, namespace `/projects/agent-memory`. Store memories, lessons and documents there. The local container (`localhost:8801`) is for development and the test suites only; do not keep knowledge in it. Settings and keys are in `.amk.env` (git-ignored, local only; never print or commit the keys). Deployment details are a document in the knowledge base (`kb.sh search "deployment VM"`). Use `bash scripts/kb.sh` from Git Bash:

- At the start of a task: `kb.sh context "<task>"` (verified lessons/decisions plus passages from the ingested docs), or `kb.sh search "<question>"` for a quick lookup before reading whole files.
- After learning something non-obvious (a new gotcha, a decision): `kb.sh learn lesson|decision|constraint "<title>" "<content>"`. It stays a proposal until the owner reviews it (`kb.sh candidates`, `kb.sh review <id> accept|reject`); the agent key cannot approve its own proposals, and agents must not use `AMK_OWNER_KEY`.
- After editing AGENTS.md, README.md or the specification: `kb.sh ingest <file>` (re-ingesting replaces the previous revision).
- The tests never touch this tenant; `provision purge` on it deletes everything.
- On the Linux server use `bash scripts/ops.sh migrate|provision|embed|backup|verify|restore` (the `.cmd` scripts are Windows-only). Changes reach it by pushing a branch the server then pulls; the server's operator runs the commands there.

### Adding a table end to end (the workflow that was verified)

@@ -193,6 +195,7 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o
- **RegExp quirks.** `Match.FirstIndex`/`Length` are byte offsets into the UTF-8 text, not character positions (contrary to the manual), so do not `Mid` with them on non-ASCII strings; use `Execute` results' `Value` or `Replace`/`Split` instead. A literal backslash or bracket inside a character class (`[^"\\]`) fails in AxonASP's pattern translation: write `\x5C`, `\x5B`, `\x5D`.
- **`G3AXON.FUNCTIONS` `AxUrlDecode` also turns `+` into a space.** It is used to decode percent-encoded UTF-8 byte runs that cannot contain `+`; do not feed it raw text.
- **Fixed-size array members fail.** `Private m_cnt(7)` in a Class gave "Subscript out of range" when used; declare `Private m_cnt()` and `ReDim m_cnt(7)` in a method.
- **`console.log` lines are decorated.** In the HTTP server they go to stdout (`docker logs`) with ANSI colour codes, a date/time and a marker before the text, and end with the text plus a newline. Write one JSON object per call and extract it with `grep -o '{"log":.*'`. `WScript.Shell` `ExpandEnvironmentStrings` reads the container's environment in the HTTP server too.
- **`VACUUM INTO` works through G3DB** and gives a consistent copy while the server is running (`scripts/backup.asp`). There is no `sqlite3` binary in the image; use the CLI with G3DB for database maintenance. `PRAGMA foreign_keys` is off, so check `PRAGMA foreign_key_check` (the backup verification fails on violations).
- **Run CLI tools as the server user.** The HTTP server runs as `axonasp`; a database file first created by a root `docker exec` was read-only to it ("attempt to write a readonly database"). `gen.cmd`, `migrate.cmd` and `provision.cmd` use `docker exec -u axonasp`.
- **PowerShell splits `read,write` into two arguments.** Quote lists passed to `provision.cmd grant`: `'"read,write"'`.


+ 4
- 1
README.md 파일 보기

@@ -61,6 +61,7 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec
- Phase 3 (part): learning loop. Agents record experiences in a session (`POST /sessions/:id/events`) and propose knowledge with evidence (`POST /learn`: a new memory, or a new revision of `target_memory_id` at `base_revision`). Another principal with `verify` reviews it (`POST /candidates/:id/review`); the author cannot approve its own candidate without `admin`. Accepting creates the memory (an identical active one is reused), or revises the target if it has not changed meanwhile (else 409 `stale_candidate`), copies the evidence with pinned target revisions and, with `"verify": true`, records a verification. `GET /memories/:id/sources` shows evidence and verifications per revision (evidence the caller cannot read is shown as `available: false`, without its id). Recall, search and context return a `query_id` and record the returned results and revisions (the query text is kept only as a hash); `POST /feedback` rates one result (useful, not_useful, incorrect, harmful). Ratings on a result's current revision adjust its rank in recall, search and context (useful raises it, incorrect/harmful halve its score per rating); results show their `feedback` counts and a warning names demoted results. A corrected memory starts without feedback. Forgetting a memory removes its evidence, verifications, feedback and telemetry rows.
- Portability: `POST /exports` writes a canonical JSON document (`format` `agent-memory-export`, `schema_version` 1, SHA-256 `integrity.digest` over the exact `data` text) with every namespace the caller can read, or the `namespace_ids` asked for: memories with all revisions and verifications, documents with revisions and chunks, and evidence links (links to targets the caller cannot read are left out and counted). Ids, revision numbers, timestamps and principal ids are kept. `POST /imports` takes that document unchanged (max 8 MiB): it needs `admin` on every target namespace (matched by path; they must exist), rebuilds content hashes and lexical indexes and queues embeddings, and is all-or-nothing (409 `import_conflict` when an id exists, 422 for a wrong format, `unsupported_schema_version` or `integrity_mismatch`). Re-exporting imported data gives the same `data`. Not in version 1: sessions, experiences, candidates, feedback, telemetry, audit events.
- Backup and restore: `scripts\backup.cmd` (see Operations below).
- Observability: every API response carries `X-Request-Id` (a caller's own `X-Request-Id` of 8-64 characters `[A-Za-z0-9._:-]` is kept for correlation; it also appears in error bodies and audit events) and writes one JSON access-log line to stdout: request id, method, controller action, status, duration, tenant and principal ids. Bodies, query strings and keys are never logged. `GET /api/v1/metrics` serves Prometheus text: request counters and a latency histogram per action (in process memory, reset by a restart), and installation-wide counts of memories, candidates, jobs, embedding index states, retrieval calls (with empty results and total time) and feedback. It needs the `AMK_METRICS_TOKEN` bearer token and answers 404 while that is unset.

**Known limitation**
- Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8).
@@ -68,8 +69,9 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec
**Tooling**
- `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`.
- `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`).
- `scripts/ops.sh`: the same tools for a Linux server (migrate, provision, embed, backup, verify, restore).
- `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model).
- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (44), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802). Each creates and purges its own tenants.
- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (44), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`). Each creates and purges its own tenants.

**Next (not started)**
1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`).
@@ -89,6 +91,7 @@ SQLite (`db/app.sqlite`) is the only source of truth. The Qdrant vectors are der

- `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings, and the `Embedding*` / `VectorStoreUrl` settings (`EmbeddingProvider` `none` turns semantic retrieval off). Settings are cached per process: `docker restart axonasp` after editing.
- First start of the semantic stack: `docker compose up -d`, then `docker exec ollama ollama pull nomic-embed-text` once (the model lives in the `ollama-models` volume). The ollama image is about 6 GB.
- Metrics: put `AMK_METRICS_TOKEN=<random, 16+ characters>` in a `.env` file in the repo root (git-ignored; compose reads it), then `docker compose up -d`. Scrape `http://<host>:8801/api/v1/metrics` with `Authorization: Bearer <token>`. Access logs: `docker logs axonasp 2>&1 | grep -o '{"log":"access".*'` (each line has a runtime timestamp prefix); `ApiAccessLog` in `web.config` turns them off.
- `/opt/axonasp/config/axonasp.toml` (inside the container): server settings; any key can be overridden with an environment variable (see `docker-compose.yml`).

## Rules for developers and AI agents


+ 92
- 0
app/controllers/ApiHealthController.asp 파일 보기

@@ -4,6 +4,11 @@
' GET /api/v1/health/live Live 200 while the process answers
' GET /api/v1/health/ready Ready 200 when the database answers (status ready, or degraded when the embedding
' provider / vector store is unreachable), else 503
' GET /api/v1/metrics Metrics Prometheus text: request counters and latency (lib.Observability.asp) plus
' installation-wide gauges (memories, candidates, jobs, embedding index,
' retrieval and feedback totals; counts only, never content or ids). Needs
' Authorization: Bearer <AMK_METRICS_TOKEN> (environment variable of the
' container, 16+ characters); while it is unset the endpoint answers 404.
Class ApiHealthController_Class
Public Property Get useLayout()
useLayout = False
@@ -77,11 +82,98 @@ Class ApiHealthController_Class
",""embedding_backlog"":{""pending"":" & pending & ",""failed"":" & failed & "}}"
End Sub

Public Sub Metrics()
Dim sh, token, auth, out, msg
Set sh = CreateObject("WScript.Shell")
token = sh.ExpandEnvironmentStrings("%AMK_METRICS_TOKEN%")
If token = "%AMK_METRICS_TOKEN%" Then
token = ""
End If
If Len(token) < 16 Then
Api_NotFound
Exit Sub
End If
auth = "" & Request.ServerVariables("HTTP_AUTHORIZATION")
' Compare digests, so the time taken does not depend on how much of the token matched.
If Api_Sha256(auth) <> Api_Sha256("Bearer " & token) Then
Response.AddHeader "WWW-Authenticate", "Bearer"
Api_Error 401, "unauthorized", "A valid metrics token is required."
Exit Sub
End If

out = Obs_RequestMetrics()
On Error Resume Next
out = out & Gauge("amk_memories", "Memories by lifecycle status.", "gauge", _
"SELECT lifecycle_status, COUNT(*) FROM memories GROUP BY 1", "status")
out = out & Gauge("amk_learning_candidates", "Learning candidates by state.", "gauge", _
"SELECT state, COUNT(*) FROM learning_candidates GROUP BY 1", "state")
out = out & Gauge("amk_jobs", "Ingestion jobs by state.", "gauge", _
"SELECT state, COUNT(*) FROM jobs GROUP BY 1", "state")
out = out & Gauge("amk_embedding_index", "Embedding index entries by status.", "gauge", _
"SELECT status, COUNT(*) FROM embedding_index GROUP BY 1", "status")
out = out & Gauge("amk_retrieval_queries_total", "Recorded retrieval calls by operation and strategy.", "counter", _
"SELECT operation, strategy, COUNT(*) FROM retrieval_queries GROUP BY 1, 2", "operation,strategy")
out = out & Gauge("amk_retrieval_empty_total", "Recorded retrieval calls that returned no results.", "counter", _
"SELECT operation, COUNT(*) FROM retrieval_queries WHERE result_count = 0 GROUP BY 1", "operation")
out = out & Gauge("amk_retrieval_duration_ms_sum", "Total recorded retrieval time in milliseconds.", "counter", _
"SELECT operation, SUM(duration_ms) FROM retrieval_queries GROUP BY 1", "operation")
out = out & Gauge("amk_feedback_total", "Usefulness feedback by rating.", "counter", _
"SELECT usefulness, COUNT(*) FROM feedback GROUP BY 1", "usefulness")
If Err.Number <> 0 Then
msg = Err.Description
Err.Clear
On Error GoTo 0
Api_Error 500, "internal_error", "Metrics query failed: " & msg
Exit Sub
End If
On Error GoTo 0

Response.Clear
Response.Status = "200 OK"
Response.ContentType = "text/plain; version=0.0.4"
Response.Charset = "utf-8"
Response.AddHeader "X-Request-Id", Api_RequestId()
Response.AddHeader "Cache-Control", "no-store"
Response.Write out
Obs_Record 200
End Sub

' One metric family from a grouped query: the label columns first, the value last.
Private Function Gauge(name, help, kind, sql, labelNames)
Dim rs, rows, names, i, r, out, labels, v
names = Split(labelNames, ",")
Set rs = DAL().Query(sql, Empty)
rows = Empty
If Not rs.EOF Then
rows = rs.GetRows()
End If
rs.Close
out = "# HELP " & name & " " & help & vbLf & "# TYPE " & name & " " & kind & vbLf
If IsArray(rows) Then
For r = 0 To UBound(rows, 2)
labels = ""
For i = 0 To UBound(names)
If i > 0 Then
labels = labels & ","
End If
labels = labels & names(i) & "=""" & Obs_Label(rows(i, r)) & """"
Next
v = rows(UBound(names) + 1, r)
If IsNull(v) Then
v = 0
End If
out = out & name & "{" & labels & "} " & v & vbLf
Next
End If
Gauge = out
End Function

' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
Public Sub Invoke(actionName, args)
Select Case LCase(actionName)
Case "live" : Live
Case "ready" : Ready
Case "metrics" : Metrics
Case Else
Err.Raise 438, "ApiHealthController_Class", "Action '" & actionName & "' not found"
End Select


+ 1
- 0
core/autoload_core.asp 파일 보기

@@ -16,6 +16,7 @@
<!--#include file="../core/lib.crypto.helper.asp"-->
<!--#include file="../core/lib.Enumerable.asp"-->
<!--#include file="../core/lib.JsonLite.asp"-->
<!--#include file="../core/lib.Observability.asp"-->
<!--#include file="../core/lib.Api.asp"-->
<!--#include file="../core/lib.Search.asp"-->
<!--#include file="../core/lib.Embeddings.asp"-->


+ 11
- 1
core/lib.Api.asp 파일 보기

@@ -40,8 +40,17 @@ Function Api_Now()
End Function

Function Api_RequestId()
Dim re, h
If Len(Api_RequestIdValue) = 0 Then
Api_RequestIdValue = "req-" & Api_NewId()
' A caller's X-Request-Id is kept for correlation when it is a plain token; otherwise a new id is made.
h = "" & Request.ServerVariables("HTTP_X_REQUEST_ID")
Set re = New RegExp
re.Pattern = "^[A-Za-z0-9._:-]{8,64}$"
If re.Test(h) Then
Api_RequestIdValue = h
Else
Api_RequestIdValue = "req-" & Api_NewId()
End If
End If
Api_RequestId = Api_RequestIdValue
End Function
@@ -94,6 +103,7 @@ Sub Api_Send(status, jsonText)
Response.AddHeader "X-Request-Id", Api_RequestId()
Response.AddHeader "Cache-Control", "no-store"
Response.Write jsonText
Obs_Record status
End Sub

Sub Api_Error(status, code, message)


+ 142
- 0
core/lib.Observability.asp 파일 보기

@@ -0,0 +1,142 @@
<%
' Observability for the JSON API (spec NFR-004, FR-019): one structured access-log line per API response and
' in-process request metrics, exposed with database gauges by GET /api/v1/metrics (ApiHealthController.Metrics).
'
' - Obs_Start is taken when this file runs (start of the request); MVC_InvokeAction sets Obs_Action to
' "<Controller>.<Action>", so metric labels stay bounded (no raw paths or ids).
' - Api_Send calls Obs_Record once per response. The log line is JSON written with console.log (stdout, so
' `docker logs axonasp`); 5xx go through console.error (stderr and the runtime's error.log). Each line has a
' timestamp/marker prefix from the runtime: extract the JSON with grep -o '{"log":.*'. No bodies, query strings
' or keys are logged. web.config ApiAccessLog = "false" turns the lines off (metrics are kept).
' - Counters live in Application (one process, reset on restart; Prometheus treats that as a counter reset).
' Requests whose action fails inside the dispatcher (empty 200, see AGENTS.md section 8) are not counted.
' Include before lib.Api.asp.
Dim Obs_Start, Obs_Action, Obs_Done
Obs_Start = Timer
Obs_Action = ""
Obs_Done = False

' Upper bounds (ms) of the latency histogram buckets; +Inf is implied.
Const OBS_BUCKETS = "5,10,25,50,100,250,500,1000,2500,5000,10000"

' Milliseconds since the request started (Timer wraps at midnight).
Function Obs_ElapsedMs()
Dim d
d = Timer - Obs_Start
If d < 0 Then
d = d + 86400
End If
Obs_ElapsedMs = Round(d * 1000, 1)
End Function

' Adds v to an Application counter and remembers the key in a registry list. Caller holds Application.Lock.
Sub Obs_Add(registry, key, v)
Dim cur
cur = Application(key)
If IsEmpty(cur) Then
Application(registry) = Application(registry) & key & vbLf
cur = 0
End If
Application(key) = cur + v
End Sub

Sub Obs_Record(status)
Dim ms, action, method, b, i, line, setting
If Obs_Done Then
Exit Sub
End If
Obs_Done = True
ms = Obs_ElapsedMs()
action = Obs_Action
If action = "" Then
action = "unrouted"
End If
method = UCase(Request.ServerVariables("REQUEST_METHOD"))

b = Split(OBS_BUCKETS, ",")
Application.Lock
If IsEmpty(Application("obs|since")) Then
Application("obs|since") = DateDiff("s", #1970-01-01#, Now())
End If
Obs_Add "obs|keys|req", "obs|req|" & action & "|" & method & "|" & status, 1
Obs_Add "obs|keys|act", "obs|n|" & action, 1
Application("obs|sum|" & action) = Application("obs|sum|" & action) + ms
For i = 0 To UBound(b)
If ms <= CDbl(b(i)) Then
Application("obs|b|" & action & "|" & i) = Application("obs|b|" & action & "|" & i) + 1
End If
Next
Application.Unlock

setting = LCase("" & GetAppSetting("ApiAccessLog"))
If setting = "false" Then
Exit Sub
End If
line = "{""log"":""access"",""request_id"":" & JsonLite_Quote(Api_RequestId()) & _
",""method"":" & JsonLite_Quote(method) & ",""action"":" & JsonLite_Quote(action) & _
",""status"":" & status & ",""duration_ms"":" & JsonLite_Num(ms) & _
",""tenant_id"":" & Obs_JStr(Api_TenantId) & ",""principal_id"":" & Obs_JStr(Api_PrincipalId) & "}"
If status >= 500 Then
console.error line
Else
console.log line
End If
End Sub

Function Obs_JStr(v)
If IsEmpty(v) Or IsNull(v) Then
Obs_JStr = "null"
ElseIf "" & v = "" Then
Obs_JStr = "null"
Else
Obs_JStr = JsonLite_Quote("" & v)
End If
End Function

' Prometheus label value escaping (backslash, quote, newline).
Function Obs_Label(s)
Obs_Label = Replace(Replace(Replace("" & s, "\", "\\"), """", "\"""), vbLf, "\n")
End Function

' Request metrics in Prometheus text format (counters and the latency histogram).
Function Obs_RequestMetrics()
Dim keys, parts, i, j, out, act, b, cum, n
out = "# HELP amk_http_requests_total API responses by action, method and status since process start." & vbLf & _
"# TYPE amk_http_requests_total counter" & vbLf
Application.Lock
keys = Split("" & Application("obs|keys|req"), vbLf)
For i = 0 To UBound(keys)
If keys(i) <> "" Then
parts = Split(keys(i), "|")
out = out & "amk_http_requests_total{action=""" & Obs_Label(parts(2)) & """,method=""" & parts(3) & _
""",status=""" & parts(4) & """} " & Application(keys(i)) & vbLf
End If
Next
out = out & "# HELP amk_http_request_duration_ms API response time in milliseconds, by action." & vbLf & _
"# TYPE amk_http_request_duration_ms histogram" & vbLf
b = Split(OBS_BUCKETS, ",")
keys = Split("" & Application("obs|keys|act"), vbLf)
For i = 0 To UBound(keys)
If keys(i) <> "" Then
act = Mid(keys(i), Len("obs|n|") + 1)
n = Application(keys(i))
For j = 0 To UBound(b)
cum = Application("obs|b|" & act & "|" & j)
If IsEmpty(cum) Then
cum = 0
End If
out = out & "amk_http_request_duration_ms_bucket{action=""" & Obs_Label(act) & """,le=""" & b(j) & """} " & cum & vbLf
Next
out = out & "amk_http_request_duration_ms_bucket{action=""" & Obs_Label(act) & """,le=""+Inf""} " & n & vbLf
out = out & "amk_http_request_duration_ms_sum{action=""" & Obs_Label(act) & """} " & _
Replace(CStr(Application("obs|sum|" & act)), ",", ".") & vbLf
out = out & "amk_http_request_duration_ms_count{action=""" & Obs_Label(act) & """} " & n & vbLf
End If
Next
out = out & "# HELP amk_process_start_time_seconds Unix time when the counters started." & vbLf & _
"# TYPE amk_process_start_time_seconds gauge" & vbLf & _
"amk_process_start_time_seconds " & Application("obs|since") & vbLf
Application.Unlock
Obs_RequestMetrics = out
End Function
%>

+ 1
- 0
core/mvc.asp 파일 보기

@@ -6,6 +6,7 @@ Function MVC_GetController(controllerName)
End Function
' Calls <Controller>_Invoke(actionName, args), defined at the bottom of each controller file.
Sub MVC_InvokeAction(controllerName, actionName, args)
Obs_Action = controllerName & "." & actionName
Dim entry : Set entry = GetRef(controllerName & "_Invoke")
entry actionName, args
End Sub


+ 2
- 0
docker-compose.yml 파일 보기

@@ -12,6 +12,8 @@ services:
# /opt/axonasp/site/db/app.sqlite. The generators (scripts/gen.cmd) and the
# migrator (scripts/migrate.cmd) also expect this layout.
SERVER_WEB_ROOT: /opt/axonasp/site/public
# GET /api/v1/metrics is enabled when this is set (16+ characters); put it in a git-ignored .env file
AMK_METRICS_TOKEN: ${AMK_METRICS_TOKEN:-}
volumes:
- .:/opt/axonasp/site
restart: unless-stopped


+ 1
- 0
public/Default.asp 파일 보기

@@ -30,6 +30,7 @@
' Health probes
router.AddRoute "GET", "/api/v1/health/live", "ApiHealthController", "Live"
router.AddRoute "GET", "/api/v1/health/ready", "ApiHealthController", "Ready"
router.AddRoute "GET", "/api/v1/metrics", "ApiHealthController", "Metrics"

' Documents, ingestion and search
router.AddRoute "POST", "/api/v1/ingestion/jobs", "ApiDocumentsController", "Ingest"


+ 40
- 0
public/api/memory-v1.openapi.json 파일 보기

@@ -2709,6 +2709,46 @@
}
}
},
"/metrics": {
"get": {
"summary": "Prometheus text metrics: API request counters and latency histogram per controller action (since process start), plus installation-wide counts (memories, candidates, jobs, embedding index, retrieval calls, feedback). Counts only. Enabled when the container has AMK_METRICS_TOKEN (16+ characters); send it as a bearer token. API keys are not accepted.",
"tags": [
"health"
],
"responses": {
"200": {
"description": "Metrics",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
},
"401": {
"description": "Missing or wrong metrics token",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Metrics are disabled (no AMK_METRICS_TOKEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/context": {
"post": {
"summary": "Assemble a token-budgeted task briefing: constraints by scope, working state, preferences, conflicts, hybrid matches and reference passages",


+ 2
- 0
public/web.config 파일 보기

@@ -45,6 +45,8 @@
docker exec ollama ollama pull nomic-embed-text
Changing the model or dimensions starts a new vector collection: run scripts\embed.cmd reindex.
-->
<!-- One JSON access-log line per API response on stdout (docker logs axonasp); "false" turns it off. -->
<add key="ApiAccessLog" value="true" />
<add key="EmbeddingProvider" value="ollama" />
<add key="EmbeddingUrl" value="http://ollama:11434" />
<add key="EmbeddingModel" value="nomic-embed-text" />


+ 40
- 0
scripts/ops.sh 파일 보기

@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Linux/macOS equivalents of the scripts\*.cmd tools, for a server deployment (run from the repo root on the host
# that runs the "axonasp" container).
#
# bash scripts/ops.sh migrate [up|down|status] schema migrations (run "up" once per pending migration)
# bash scripts/ops.sh provision <action> [args...] same actions as scripts\provision.cmd
# bash scripts/ops.sh embed [status|run|reindex] semantic index maintenance
# bash scripts/ops.sh backup [file] online backup to db/backups/ and verification
# bash scripts/ops.sh verify <file> verify a backup file
# bash scripts/ops.sh restore <file> stop, verify, restore, start, reindex (see README)
set -eu
cd "$(dirname "$0")/.."
cli() { docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site "$@"; }
cmd=${1:-}; [ $# -gt 0 ] && shift
case "$cmd" in
migrate)
cli -e "MIGRATE=${1:-up}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp ;;
provision)
[ $# -ge 1 ] || { echo "usage: ops.sh provision <action> [args...]" >&2; exit 1; }
cli -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp ;;
embed)
cli -e "EMBED_ACTION=${1:-status}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp ;;
backup|verify)
cli -e "BACKUP_ACTION=$cmd" -e "BACKUP_FILE=${1:-}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp ;;
restore)
[ $# -ge 1 ] || { echo "usage: ops.sh restore db/backups/<file>.sqlite" >&2; exit 1; }
docker compose stop axonasp embed-worker
log=$(docker compose run --rm --no-deps -T -e SERVER_WEB_ROOT=/opt/axonasp/site -e BACKUP_ACTION=restore \
-e "BACKUP_FILE=$1" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 || true)
echo "$log"
docker compose start axonasp embed-worker
if ! grep -q '^RESULT: ok' <<<"$log"; then
echo "Restore FAILED, see above. If the copy had started, the previous database is in db/backups/pre-restore-*.sqlite." >&2
exit 1
fi
"$0" embed reindex ;;
*)
sed -n '2,11p' "$0"; exit 1 ;;
esac

+ 99
- 0
tests/observability.sh 파일 보기

@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# Observability checks (spec NFR-004, FR-019): correlation ids (a caller's X-Request-Id is echoed and logged, an
# unsafe one is replaced), one structured access-log line per API response without secrets, request counters and a
# latency histogram, installation-wide gauges, and the metrics endpoint's protection (token, method, disabled state).
#
# Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). The metrics checks
# need AMK_METRICS_TOKEN set for the container (git-ignored .env, then docker compose up -d); without it only the
# "disabled -> 404" check runs. Restarts the container once; creates and purges a throw-away tenant.
# bash tests/observability.sh
set -u
BASE=${BASE:-http://localhost:8801/api/v1}
PASS=0; FAIL=0; FAILED=(); TENANT=""
prov() {
MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
-e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\015'
}
field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
cleanup() { [ -n "$TENANT" ] && prov purge "$TENANT" >/dev/null; }
trap cleanup EXIT
restart() { docker restart axonasp >/dev/null; for i in $(seq 1 30); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done; }
# access-log JSON lines written since the container started
logs() { docker logs axonasp 2>&1 | grep -o '{"log":"access".*'; }
TOKEN=$(MSYS_NO_PATHCONV=1 docker exec axonasp printenv AMK_METRICS_TOKEN 2>/dev/null | tr -d '\015')
metrics() { curl -s -H "Authorization: Bearer $TOKEN" "$BASE/metrics"; }
# value of one sample line, e.g. metric 'amk_http_requests_total{action="ApiHealthController.Live",method="GET",status="200"}'
sample() { grep -F "$1 " | grep -v "^#" | head -1 | awk '{print $NF}'; }

TENANT=$(prov tenant "obs" | field tenant_id)
OUT=$(prov principal "$TENANT" obs-agent agent); PID=$(echo "$OUT" | field principal_id); KEY=$(echo "$OUT" | field api_key)
prov grant "$PID" /obs "read,write" 1 >/dev/null
NS=$(prov namespace "$TENANT" /obs | field namespace_id)
[ -n "$NS" ] && [ -n "$KEY" ] || { echo "setup failed"; exit 2; }

restart
# ---- correlation ids and access log ------------------------------------------------------------------------------
RID="obs-test-$RANDOM-$RANDOM"
H=$(curl -s -D - -o /dev/null -H "X-Request-Id: $RID" -H "Authorization: Bearer $KEY" -X POST "$BASE/remember" \
-d "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"Obs\",\"content\":\"secret-ish body text 4711\"}" | tr -d '\015')
check "cold: write with caller request id -> 201" "201" "$(echo "$H" | sed -n 's/^HTTP\/[0-9.]* \([0-9]*\).*/\1/p' | head -1)"
check "caller X-Request-Id echoed" "$RID" "$(echo "$H" | sed -n 's/^[Xx]-[Rr]equest-[Ii]d: *//p')"
BADH=$(curl -s -D - -o /dev/null -H 'X-Request-Id: bad id with spaces' "$BASE/health/live" | tr -d '\015' | sed -n 's/^[Xx]-[Rr]equest-[Ii]d: *//p')
check "unsafe X-Request-Id replaced" "yes" "$([[ "$BADH" == req-* ]] && echo yes || echo no)"
LONGH=$(curl -s -D - -o /dev/null -H "X-Request-Id: $(printf 'a%.0s' $(seq 1 80))" "$BASE/health/live" | tr -d '\015' | sed -n 's/^[Xx]-[Rr]equest-[Ii]d: *//p')
check "over-long X-Request-Id replaced" "yes" "$([[ "$LONGH" == req-* ]] && echo yes || echo no)"
ERR=$(curl -s -H "X-Request-Id: $RID-404" -H "Authorization: Bearer $KEY" "$BASE/memories/00000000-0000-0000-0000-000000000000")
check "error body carries the request id" "yes" "$(grep -q "\"request_id\":\"$RID-404\"" <<<"$ERR" && echo yes || echo no)"
LINE=$(logs | grep -F "\"request_id\":\"$RID\"" | head -1)
check "access log line for the write" "201 ApiMemoriesController.Remember POST $TENANT $PID" \
"$(python -I -c "import sys,json;d=json.loads(sys.argv[1]);print(d['status'],d['action'],d['method'],d['tenant_id'],d['principal_id'])" "$LINE" 2>&1)"
check "access log has a duration" "yes" "$(python -I -c "import sys,json;d=json.loads(sys.argv[1]);print('yes' if d['duration_ms']>=0 else 'no')" "$LINE" 2>&1)"
check "404 logged with its request id" "404" "$(logs | grep -F "\"request_id\":\"$RID-404\"" | python -I -c "import sys,json;print(json.loads(sys.stdin.readline())['status'])" 2>&1)"
ALL=$(docker logs axonasp 2>&1)
check "no API key in the logs" "no" "$(grep -qF "$KEY" <<<"$ALL" && echo yes || echo no)"
check "no request body in the logs" "no" "$(grep -qF "secret-ish body text 4711" <<<"$ALL" && echo yes || echo no)"
check "unauthenticated request logged without identity" "null" "$(logs | grep -F '"action":"ApiHealthController.Live"' | tail -1 | python -I -c "import sys,json;print(json.dumps(json.loads(sys.stdin.readline())['tenant_id']))" 2>&1)"

# ---- metrics -----------------------------------------------------------------------------------------------------
if [ ${#TOKEN} -lt 16 ]; then
check "metrics disabled without a token -> 404" "404" "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/metrics")"
echo "AMK_METRICS_TOKEN is not set for the container: metrics checks skipped"
else
check "metrics without token -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/metrics")"
check "metrics with an API key -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $KEY" "$BASE/metrics")"
check "metrics wrong method -> 405" "405" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $TOKEN" "$BASE/metrics")"
check "metrics content type" "text/plain; version=0.0.4; charset=utf-8" \
"$(curl -s -D - -o /dev/null -H "Authorization: Bearer $TOKEN" "$BASE/metrics" | tr -d '\015' | sed -n 's/^[Cc]ontent-[Tt]ype: *//p')"
LIVE='amk_http_requests_total{action="ApiHealthController.Live",method="GET",status="200"}'
B1=$(metrics | sample "$LIVE"); B1=${B1:-0}
for i in 1 2 3 4 5; do curl -s -o /dev/null "$BASE/health/live"; done
M=$(metrics)
check "request counter counts exactly" "$((B1 + 5))" "$(echo "$M" | sample "$LIVE")"
check "401s are counted" "yes" "$(echo "$M" | grep -q 'action="ApiHealthController.Metrics",method="GET",status="401"' && echo yes || echo no)"
check "write is counted" "1" "$(echo "$M" | sample 'amk_http_requests_total{action="ApiMemoriesController.Remember",method="POST",status="201"}')"
check "histogram +Inf bucket equals count" "yes" "$(echo "$M" | python -I -c "
import sys,re
t=sys.stdin.read()
inf=re.search(r'amk_http_request_duration_ms_bucket\{action=\"ApiHealthController.Live\",le=\"\+Inf\"\} (\d+)',t).group(1)
cnt=re.search(r'amk_http_request_duration_ms_count\{action=\"ApiHealthController.Live\"\} (\d+)',t).group(1)
b=[int(x) for x in re.findall(r'amk_http_request_duration_ms_bucket\{action=\"ApiHealthController.Live\",le=\"[0-9]+\"\} (\d+)',t)]
print('yes' if inf==cnt and b==sorted(b) and b[-1]<=int(inf) else 'no')")"
check "gauges: memories" "yes" "$(echo "$M" | grep -q '^amk_memories{status="active"} [0-9]' && echo yes || echo no)"
curl -s -o /dev/null -H "Authorization: Bearer $KEY" -X POST "$BASE/recall" -d '{"query":"zzqx unmatched term"}'
M2=$(metrics)
R1=$(echo "$M" | sample 'amk_retrieval_empty_total{operation="recall"}'); R2=$(echo "$M2" | sample 'amk_retrieval_empty_total{operation="recall"}')
check "retrieval metrics: empty recall counted" "$(( ${R1:-0} + 1 ))" "${R2:-0}"
check "metrics carry no tenant ids" "no" "$(grep -qF "$TENANT" <<<"$M2" && echo yes || echo no)"
check "metrics every line well-formed" "0" "$(echo "$M2" | grep -v '^# \(HELP\|TYPE\) ' | grep -cvE '^[a-z_]+(\{[a-z_]+="[^"]*"(,[a-z_]+="[^"]*")*\})? -?[0-9.e+]+$')"
S1=$(echo "$M2" | sample amk_process_start_time_seconds)
sleep 1; restart
M3=$(metrics)
check "restart resets counters" "1" "$(echo "$M3" | grep -c '^amk_http_requests_total')"
check "restart moves the start time" "yes" "$([ "$(echo "$M3" | sample amk_process_start_time_seconds)" -gt "${S1:-0}" ] && echo yes || echo no)"
fi

echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

불러오는 중...
취소
저장

Powered by TurnKey Linux.