#1 Durable ingestion jobs; transactions refuse to commit after a failed statement

Sloučený
dcovington sloučil 1 revizí z větve phase3-context do větve master před před 21 hodinami
  1. +3
    -1
      AGENTS.md
  2. +2
    -1
      README.md
  3. +129
    -132
      app/controllers/ApiDocumentsController.asp
  4. +1
    -0
      core/autoload_core.asp
  5. +18
    -1
      core/lib.Data.asp
  6. +326
    -0
      core/lib.Jobs.asp
  7. +40
    -0
      db/migrations/20261205155214_add_payload_to_jobs.asp
  8. +1
    -0
      public/Default.asp
  9. +177
    -3
      public/api/memory-v1.openapi.json
  10. +12
    -4
      scripts/embed.asp
  11. +1
    -0
      scripts/embed.cmd
  12. +35
    -0
      tests/fixtures/job_state.asp
  13. +139
    -0
      tests/phase3-jobs.sh

+ 3
- 1
AGENTS.md Zobrazit soubor

@@ -38,10 +38,11 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w
- Phase 3 (context): `ApiContextController` (`POST /context`) assembles a budgeted briefing. Constraints are loaded by scope (not similarity) and are required: if they do not fit `max_context_tokens` the answer is 422 `context_budget_exceeded`. Regression suite: `bash tests/phase3-context.sh`. - Phase 3 (context): `ApiContextController` (`POST /context`) assembles a budgeted briefing. Constraints are loaded by scope (not similarity) and are required: if they do not fit `max_context_tokens` the answer is 422 `context_budget_exceeded`. Regression suite: `bash tests/phase3-context.sh`.
- Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items.
- 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`. - 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`.
- Ingestion jobs: `core/lib.Jobs.asp` (`Job_Create`, `Job_Claim`, `Job_RunIngest`, `Job_ProcessDue`), shared by `ApiDocumentsController.Ingest` and the worker (`scripts/embed.asp`, actions `jobs` and `worker`). Claim jobs only with `Job_Claim` (conditional UPDATE) and keep publishing plus the job update in one transaction. Regression suite: `bash tests/phase3-jobs.sh` (uses `tests/fixtures/job_state.asp` to simulate interruptions).
- 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`. - 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. - 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.
- 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`. - 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`).
- The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all nine suites (`tests/*.sh`).


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


@@ -167,6 +168,7 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o
- **Class-level `Const` is Empty.** `Private Const X = 10` inside a `Class` evaluates to Empty in methods (no error, so e.g. `per_page` silently became 0 and paging broke). Declare `Const` at top level, outside the class, with a prefixed name. - **Class-level `Const` is Empty.** `Private Const X = 10` inside a `Class` evaluates to Empty in methods (no error, so e.g. `per_page` silently became 0 and paging broke). Declare `Const` at top level, outside the class, with a prefixed name.
- **G3JSON.Parse and G3DB interfere under the HTTP server.** Verified: parsing a request body with `G3JSON.Parse` before the first database open in the process made the first INSERT silently do nothing (201 with `id` 0, no row), and only on the first POST after a restart; opening the database first made `Parse` return dictionaries whose `Exists`/`Item` returned stale values. Dictionaries built in a Function and returned also came back empty, and the first native call after another native call could return the previous value. For API controllers use `core/lib.JsonLite.asp` (pure VBScript: `JsonLite_Parse` -> object with `.Exists(k)`/`.Item(k)` (call `.Item`, there is no default member), `JsonLite_Quote`, `JsonLite_Num`) and compose output JSON as text. Plain VBScript classes are safe; native objects held across other native calls are not. - **G3JSON.Parse and G3DB interfere under the HTTP server.** Verified: parsing a request body with `G3JSON.Parse` before the first database open in the process made the first INSERT silently do nothing (201 with `id` 0, no row), and only on the first POST after a restart; opening the database first made `Parse` return dictionaries whose `Exists`/`Item` returned stale values. Dictionaries built in a Function and returned also came back empty, and the first native call after another native call could return the previous value. For API controllers use `core/lib.JsonLite.asp` (pure VBScript: `JsonLite_Parse` -> object with `.Exists(k)`/`.Item(k)` (call `.Item`, there is no default member), `JsonLite_Quote`, `JsonLite_Num`) and compose output JSON as text. Plain VBScript classes are safe; native objects held across other native calls are not.
- **`Request.BinaryRead(n)` returns one character per byte** (raw UTF-8 bytes), not decoded text. Decode UTF-8 yourself (`Utf8Decode` in the API controllers, which maps invalid bytes to U+FFFD); `ADODB.Stream` was unreliable too. `MSXML2.ServerXMLHTTP` works in the CLI for calling the local server, which is a handy way to write an HTTP smoke test (`axonasp-cli -r script.asp` inside the container, base URL `http://localhost:8801`). - **`Request.BinaryRead(n)` returns one character per byte** (raw UTF-8 bytes), not decoded text. Decode UTF-8 yourself (`Utf8Decode` in the API controllers, which maps invalid bytes to U+FFFD); `ADODB.Stream` was unreliable too. `MSXML2.ServerXMLHTTP` works in the CLI for calling the local server, which is a handy way to write an HTTP smoke test (`axonasp-cli -r script.asp` inside the container, base URL `http://localhost:8801`).
- **A DAL call resets `Err`.** Under `On Error Resume Next`, any later `DAL()` call sets `Err.Number` back to 0 (plain functions, subs and builtins do not). A transaction that runs several statements and checks `Err` once before committing therefore lost an early failure and committed a partial write: two concurrent ingests of the same `source_uri` produced a second document without its `source_uri` (the unique-index violation was wiped). `Database_Class` now remembers the first error raised inside an open transaction and `CommitTransaction` rolls back and raises instead of committing. Still check `Err` after `CommitTransaction`, and do not rely on catching a failed statement inside a transaction and carrying on: the commit will refuse.
- **The dispatcher swallows action errors.** `Dispatch`/`ExecuteControllerAction` in `core/mvc.asp` run under `On Error Resume Next`, so an error inside an action aborts it and the response is an empty `200` (or a half page) with no message. For write paths wrap the DB call in a local `On Error Resume Next`, check `Err.Number` straight after it and answer with a real error (the API controllers send a JSON 500 via `DbFailed`). When something "does nothing", test the same code from a plain page or the CLI to see the real error. - **The dispatcher swallows action errors.** `Dispatch`/`ExecuteControllerAction` in `core/mvc.asp` run under `On Error Resume Next`, so an error inside an action aborts it and the response is an empty `200` (or a half page) with no message. For write paths wrap the DB call in a local `On Error Resume Next`, check `Err.Number` straight after it and answer with a real error (the API controllers send a JSON 500 via `DbFailed`). When something "does nothing", test the same code from a plain page or the CLI to see the real error.
- **Always test cold.** After `docker restart axonasp`, send the write request (POST/PUT/DELETE) first, before any GET: some bugs only appear on the first request after a start. Debugging aid: `Response.Clear` wipes the body, but `Response.AddHeader "X-Dbg-1", "..."` survives, so trace with headers (`curl -i`). When patching with scripts, assert that each replacement matched (a silent no-op edit cost hours here). - **Always test cold.** After `docker restart axonasp`, send the write request (POST/PUT/DELETE) first, before any GET: some bugs only appear on the first request after a start. Debugging aid: `Response.Clear` wipes the body, but `Response.AddHeader "X-Dbg-1", "..."` survives, so trace with headers (`curl -i`). When patching with scripts, assert that each replacement matched (a silent no-op edit cost hours here).
- **Operator precedence:** `"ok=" & Not (x Is Nothing)` raises Type mismatch. Put the `Not ...` in a variable first. - **Operator precedence:** `"ok=" & Not (x Is Nothing)` raises Type mismatch. Put the `Not ...` in a variable first.


+ 2
- 1
README.md Zobrazit soubor

@@ -59,6 +59,7 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec
- Phase 3 (part): `POST /context` assembles a task briefing under a token budget: constraints loaded by scope (required; 422 `context_budget_exceeded` when they do not fit), working state from a session checkpoint, preferences, disputed items as conflicts, decisions/lessons/knowledge and reference passages by hybrid match, optional unverified items; deduplicated and trust-labelled. - Phase 3 (part): `POST /context` assembles a task briefing under a token budget: constraints loaded by scope (required; 422 `context_budget_exceeded` when they do not fit), working state from a session checkpoint, preferences, disputed items as conflicts, decisions/lessons/knowledge and reference passages by hybrid match, optional unverified items; deduplicated and trust-labelled.
- Phase 3 (part): semantic retrieval. Embeddings from a local Ollama model (`nomic-embed-text`), vectors in Qdrant, both as containers in `docker-compose.yml`. `/recall`, `/search` and `/context` fuse lexical and vector ranks (reciprocal rank fusion) and fall back to lexical with a warning when the provider is off or down. SQLite stays the source of truth: `embedding_index` tracks model, dimensions, revision and status per memory/chunk, writes index after commit (never failing the write), and `scripts\embed.cmd status|run|reindex` catches up or rebuilds. Common English stopwords are dropped from lexical queries. The `embed-worker` container retries pending/failed items every 30 seconds; `GET /health/ready` reports `degraded` (still 200) and the backlog when the provider or vector store is down. - Phase 3 (part): semantic retrieval. Embeddings from a local Ollama model (`nomic-embed-text`), vectors in Qdrant, both as containers in `docker-compose.yml`. `/recall`, `/search` and `/context` fuse lexical and vector ranks (reciprocal rank fusion) and fall back to lexical with a warning when the provider is off or down. SQLite stays the source of truth: `embedding_index` tracks model, dimensions, revision and status per memory/chunk, writes index after commit (never failing the write), and `scripts\embed.cmd status|run|reindex` catches up or rebuilds. Common English stopwords are dropped from lexical queries. The `embed-worker` container retries pending/failed items every 30 seconds; `GET /health/ready` reports `degraded` (still 200) and the backlog when the provider or vector store is down.
- 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. - 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.
- Durable ingestion jobs: `POST /ingestion/jobs` stores the job and its input before processing, so nothing acknowledged is lost. By default it is processed inside the request (201, or 200 when unchanged); with `"async": true` the answer is 202 with the job and the embed-worker publishes it. A job interrupted mid-ingest (lease of 5 minutes) or failed with an internal error is retried by the worker, at most 3 attempts; other failures (unreadable input, namespace gone, permission lost, re-checked at processing time) wait for `POST /jobs/:id/retry`. Identical text is a no-op and publishing happens in one transaction with the job update, so retries and duplicate submissions never publish duplicate chunks. `GET /jobs/:id` shows state, attempts, `auto_retry` and the error.
- 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. - 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). - 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. - 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.
@@ -71,7 +72,7 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec
- `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). - `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/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). - `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), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`). 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/phase3-jobs.sh` (41; stops the embed-worker container while it runs), `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)** **Next (not started)**
1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`). 1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`).


+ 129
- 132
app/controllers/ApiDocumentsController.asp Zobrazit soubor

@@ -3,12 +3,16 @@
' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (chunker, FTS). ' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (chunker, FTS).
' '
' POST /api/v1/ingestion/jobs Ingest {"namespace_id","title","content","format":"markdown|text","source_uri"} ' POST /api/v1/ingestion/jobs Ingest {"namespace_id","title","content","format":"markdown|text","source_uri"}
' GET /api/v1/jobs/:id Job job state
' POST /api/v1/ingestion/jobs Ingest ... "async": true -> 202 with the queued job (the worker processes it)
' GET /api/v1/jobs/:id Job job state, attempts, errors
' POST /api/v1/jobs/:id/retry Retry requeue a failed job (write permission; 202)
' GET /api/v1/documents/:id Document metadata (?include_content=true adds the text) ' GET /api/v1/documents/:id Document metadata (?include_content=true adds the text)
' GET /api/v1/chunks/:id Chunk one passage with its source locator ' GET /api/v1/chunks/:id Chunk one passage with its source locator
' POST /api/v1/search Search {"query","namespace_ids":[],"max_results","detail_level":"full|snippet"} ' POST /api/v1/search Search {"query","namespace_ids":[],"max_results","detail_level":"full|snippet"}
' '
' Ingestion is processed inside the request (no worker yet) but is recorded as a job. The same source_uri in a
' Ingestion is a durable job (core/lib.Jobs.asp): the job and its input are stored first, then processed inside the
' request (201/200) or, with "async": true, by the worker (202). An interrupted or failed job is retried by the
' worker with bounded attempts. The same source_uri in a
' namespace is one document; re-ingesting changed text creates a new revision and only the current revision is ' namespace is one document; re-ingesting changed text creates a new revision and only the current revision is
' searchable. Identical text is a no-op, so retries never publish duplicate chunks. The service never fetches the ' searchable. Identical text is a no-op, so retries never publish duplicate chunks. The service never fetches the
' source_uri: it is only stored as an identifier (no SSRF surface). ' source_uri: it is only stored as an identifier (no SSRF surface).
@@ -33,7 +37,7 @@ Class ApiDocumentsController_Class
'--------------------------------------------------------------- '---------------------------------------------------------------
Public Sub Ingest() Public Sub Ingest()
Dim body, input, idemKey, reqHash, nsId, title, content, fmt, sourceUri, norm, hash Dim body, input, idemKey, reqHash, nsId, title, content, fmt, sourceUri, norm, hash
Dim rs, docId, curRev, revNo, jobId, ts, unchanged, k, resp, i, chunkId, isMd, statusCode, chunkTotal
Dim jobId, k, resp, isAsync, payload


If Not Api_Authenticate() Then Exit Sub If Not Api_Authenticate() Then Exit Sub
body = Api_ReadBody() body = Api_ReadBody()
@@ -67,42 +71,45 @@ Class ApiDocumentsController_Class
Exit Sub Exit Sub
End If End If


isMd = (fmt = "markdown")
norm = Chunk_Normalize(content)
hash = Api_Sha256(norm)

' Find an existing document: by source_uri when given, otherwise by identical title and text
docId = ""
curRev = 0
If Not IsNull(sourceUri) Then
Set rs = DAL().Query("SELECT id, current_revision FROM documents WHERE tenant_id = ? AND namespace_id = ? AND source_uri = ?", Array(Api_TenantId, nsId, sourceUri))
isAsync = False
If input.Exists("async") Then
If VarType(input.Item("async")) = vbBoolean Then
isAsync = input.Item("async")
Else Else
Set rs = DAL().Query("SELECT d.id, d.current_revision FROM documents d JOIN document_revisions r ON r.document_id = d.id AND r.revision = d.current_revision " & _
"WHERE d.tenant_id = ? AND d.namespace_id = ? AND d.source_uri IS NULL AND d.title = ? AND r.content_hash = ?", Array(Api_TenantId, nsId, title, hash))
Api_Invalid Array("async must be true or false.")
Exit Sub
End If End If
If Not rs.EOF Then
docId = "" & rs(0)
curRev = CLng(rs(1))
End If End If
rs.Close


unchanged = False
If Len(docId) > 0 Then
Set rs = DAL().Query("SELECT content_hash, chunk_count FROM document_revisions WHERE document_id = ? AND revision = ?", Array(docId, curRev))
If Not rs.EOF Then
If "" & rs(0) = hash Then
unchanged = True
chunkTotal = CLng(rs(1))
' The job and its input are stored first (durable acknowledgement, spec FR-016); see core/lib.Jobs.asp.
payload = Job_Payload(nsId, title, fmt, sourceUri, content)
On Error Resume Next
If isAsync Then
DAL().BeginTransaction
jobId = Job_Create(Api_TenantId, Api_PrincipalId, nsId, payload, False)
resp = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""queued""},""status_url"":" & JsonLite_Quote("/api/v1/jobs/" & jobId) & "}"
Api_IdempotencyStore idemKey, reqHash, 202, resp
If Err.Number <> 0 Then
k = Err.Number : Api_NoteDbError
Err.Clear
DAL().RollbackTransaction
Api_DbFailed k, ""
Exit Sub
End If End If
DAL().CommitTransaction
If Err.Number <> 0 Then
k = Err.Number : Api_NoteDbError
Api_DbFailed k, ""
Exit Sub
End If End If
rs.Close
On Error GoTo 0
Api_Audit "document.ingest", "job", jobId, "queued"
Response.AddHeader "Location", "/api/v1/jobs/" & jobId
Api_Send 202, resp
Exit Sub
End If End If


jobId = Api_NewId()
ts = Api_Now()
On Error Resume Next
DAL().Execute "INSERT INTO jobs (id, tenant_id, type, state, attempt_count, input_ref, created_by, created_at, updated_at) VALUES (?, ?, 'ingest', 'running', 1, ?, ?, ?, ?)", _
Array(jobId, Api_TenantId, nsId, Api_PrincipalId, ts, ts)
jobId = Job_Create(Api_TenantId, Api_PrincipalId, nsId, payload, True)
If Err.Number <> 0 Then If Err.Number <> 0 Then
k = Err.Number : Api_NoteDbError k = Err.Number : Api_NoteDbError
Api_DbFailed k, "" Api_DbFailed k, ""
@@ -110,93 +117,103 @@ Class ApiDocumentsController_Class
End If End If
On Error GoTo 0 On Error GoTo 0


If unchanged Then
DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, Api_Now(), jobId)
resp = IngestJson(jobId, docId, curRev, chunkTotal, True)
On Error Resume Next
Api_IdempotencyStore idemKey, reqHash, 200, resp
On Error GoTo 0
Api_Audit "document.ingest", "document", docId, "unchanged"
Api_Send 200, resp
If Not Job_RunIngest(jobId, idemKey, reqHash) Then
Api_Audit "document.ingest", "job", jobId, "failed"
If Job_ErrCode = "internal_error" Then
Response.AddHeader "Location", "/api/v1/jobs/" & jobId
Api_Error 500, "internal_error", "Ingestion failed; the input is kept and job " & jobId & " is retried automatically (GET /api/v1/jobs/" & jobId & ")."
Else
Api_Error 409, Job_ErrCode, Job_ErrMessage
End If
Exit Sub Exit Sub
End If End If


' Chunk first (pure computation), then write everything in one transaction
Chunk_Run content, isMd
If Len(docId) = 0 Then
docId = Api_NewId()
revNo = 1
Emb_AfterWrite Api_TenantId, 64
If Job_HttpStatus = 200 Then
Api_Audit "document.ingest", "document", Job_DocId, "unchanged"
Else Else
revNo = curRev + 1
Api_Audit "document.ingest", "document", Job_DocId, "ok"
Response.AddHeader "Location", "/api/v1/documents/" & Job_DocId
End If End If
Api_Send Job_HttpStatus, Job_Resp
End Sub


On Error Resume Next
DAL().BeginTransaction
If revNo = 1 Then
DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
Array(docId, Api_TenantId, nsId, fmt, title, Api_PrincipalId, ts, ts)
If Not IsNull(sourceUri) Then
DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(sourceUri, docId)
End If
Else
DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev)
Emb_MarkDeleteChunks docId, curRev
End If
DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & revNo & ", ?, ?, " & Len(norm) & ", " & Chunk_Count & ", ?, ?)", _
Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts)
For i = 0 To Chunk_Count - 1
chunkId = Api_NewId()
DAL().Execute "INSERT INTO chunks (id, document_id, document_revision, ordinal, content, heading_path, start_offset, end_offset, token_estimate, created_at) VALUES (?, ?, " & revNo & ", " & i & ", ?, ?, " & Chunk_Start(i) & ", " & Chunk_End(i) & ", " & TokenEstimate(Chunk_Text(i)) & ", ?)", _
Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts)
DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _
Array(Chunk_Text(i), chunkId, Api_TenantId, nsId)
Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo
Next
If revNo > 1 Then
DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId)
End If
DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
resp = IngestJson(jobId, docId, revNo, Chunk_Count, False)
Api_IdempotencyStore idemKey, reqHash, 201, resp
If Err.Number <> 0 Then
k = Err.Number : Api_NoteDbError
Err.Clear
DAL().RollbackTransaction
MarkJobFailed jobId, "internal_error", Api_LastDbError
Api_DbFailed k, ""
'---------------------------------------------------------------
' GET /api/v1/jobs/:id
'---------------------------------------------------------------
Public Sub Job(id)
Dim rs, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs, retryable

If Not Api_Authenticate() Then Exit Sub
If Not LoadJob(id, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs) Then
Api_NotFound
Exit Sub Exit Sub
End If End If
DAL().CommitTransaction
If Err.Number <> 0 Then
k = Err.Number : Api_NoteDbError
Api_DbFailed k, ""
If Not JobVisible(createdBy, resultRef, inputNs) Then
Api_NotFound
Exit Sub Exit Sub
End If End If
On Error GoTo 0


Emb_AfterWrite Api_TenantId, 64
Api_Audit "document.ingest", "document", docId, "ok"
Response.AddHeader "Location", "/api/v1/documents/" & docId
Api_Send 201, resp
retryable = False
If state = "failed" Then
If "" & errCode = "internal_error" Then
retryable = (attempts < JOB_MAX_ATTEMPTS)
End If
End If
Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":" & JsonLite_Quote(state) & _
",""attempts"":" & attempts & ",""max_attempts"":" & JOB_MAX_ATTEMPTS & ",""auto_retry"":" & LCase(CStr(retryable)) & _
",""document_id"":" & JStr(resultRef) & ",""error_code"":" & JStr(errCode) & ",""error_message"":" & JStr(errMsg) & _
",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & "}"
End Sub End Sub


'--------------------------------------------------------------- '---------------------------------------------------------------
' GET /api/v1/jobs/:id
' POST /api/v1/jobs/:id/retry (failed jobs only; write permission on the job's namespace)
'--------------------------------------------------------------- '---------------------------------------------------------------
Public Sub Job(id)
Dim rs, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, allowed, nsId
Public Sub Retry(id)
Dim jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs, r, k


If Not Api_Authenticate() Then Exit Sub If Not Api_Authenticate() Then Exit Sub
If Not Api_IsId(id) Then
If Not LoadJob(id, jType, state, attempts, resultRef, errCode, errMsg, createdBy, createdAt, updatedAt, inputNs) Then
Api_NotFound Api_NotFound
Exit Sub Exit Sub
End If End If
Set rs = DAL().Query("SELECT type, state, attempt_count, result_ref, error_code, error_message, created_by, created_at, updated_at FROM jobs WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
If rs.EOF Then
rs.Close
If Not Api_CanAccessNamespace(inputNs, "write") Then
Api_Audit "job.retry", "job", id, "denied"
Api_NotFound Api_NotFound
Exit Sub Exit Sub
End If End If
If state <> "failed" Then
Api_Error 409, "job_not_retryable", "Only failed jobs can be retried; this job is " & state & "."
Exit Sub
End If
On Error Resume Next
Set r = DAL().Exec("UPDATE jobs SET state = 'queued', attempt_count = 0, error_code = NULL, error_message = NULL, updated_at = ? " & _
"WHERE id = ? AND tenant_id = ? AND state = 'failed' AND payload IS NOT NULL", Array(Api_Now(), id, Api_TenantId))
If Err.Number <> 0 Then
k = Err.Number : Api_NoteDbError
Api_DbFailed k, ""
Exit Sub
End If
On Error GoTo 0
If r.RowsAffected <> 1 Then
Api_Error 409, "job_not_retryable", "The job's input is no longer stored; submit the document again."
Exit Sub
End If
Api_Audit "job.retry", "job", id, "queued"
Response.AddHeader "Location", "/api/v1/jobs/" & id
Api_Send 202, "{""job"":{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":""queued""},""status_url"":" & JsonLite_Quote("/api/v1/jobs/" & id) & "}"
End Sub

' Reads a job of the caller's tenant; False when it does not exist.
Private Function LoadJob(id, ByRef jType, ByRef state, ByRef attempts, ByRef resultRef, ByRef errCode, ByRef errMsg, ByRef createdBy, ByRef createdAt, ByRef updatedAt, ByRef inputNs)
Dim rs
LoadJob = False
If Not Api_IsId(id) Then Exit Function
Set rs = DAL().Query("SELECT type, state, attempt_count, result_ref, error_code, error_message, created_by, created_at, updated_at, input_ref FROM jobs WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
If rs.EOF Then
rs.Close
Exit Function
End If
jType = "" & rs(0) jType = "" & rs(0)
state = "" & rs(1) state = "" & rs(1)
attempts = CLng(rs(2)) attempts = CLng(rs(2))
@@ -206,23 +223,27 @@ Class ApiDocumentsController_Class
createdBy = "" & rs(6) createdBy = "" & rs(6)
createdAt = "" & rs(7) createdAt = "" & rs(7)
updatedAt = "" & rs(8) updatedAt = "" & rs(8)
inputNs = "" & rs(9)
rs.Close rs.Close
LoadJob = True
End Function


' The submitter always sees the job; others need read access to the document it produced
allowed = (createdBy = Api_PrincipalId)
If Not allowed And Not IsNull(resultRef) Then
' The submitter always sees the job; others need read access to the document it produced or to its namespace.
Private Function JobVisible(createdBy, resultRef, inputNs)
Dim nsId
JobVisible = (createdBy = Api_PrincipalId)
If JobVisible Then Exit Function
If Not IsNull(resultRef) Then
nsId = DocNamespace("" & resultRef) nsId = DocNamespace("" & resultRef)
If Len(nsId) > 0 Then allowed = Api_CanAccessNamespace(nsId, "read")
If Len(nsId) > 0 Then
JobVisible = Api_CanAccessNamespace(nsId, "read")
Exit Function
End If End If
If Not allowed Then
Api_NotFound
Exit Sub
End If End If

Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""type"":" & JsonLite_Quote(jType) & ",""state"":" & JsonLite_Quote(state) & _
",""attempts"":" & attempts & ",""document_id"":" & JStr(resultRef) & ",""error_code"":" & JStr(errCode) & ",""error_message"":" & JStr(errMsg) & _
",""created_at"":" & JsonLite_Quote(createdAt) & ",""updated_at"":" & JsonLite_Quote(updatedAt) & "}"
End Sub
If Len(inputNs) > 0 Then
JobVisible = Api_CanAccessNamespace(inputNs, "read")
End If
End Function


'--------------------------------------------------------------- '---------------------------------------------------------------
' GET /api/v1/documents/:id (?include_content=true) ' GET /api/v1/documents/:id (?include_content=true)
@@ -439,19 +460,6 @@ Class ApiDocumentsController_Class
ChunkJson = s ChunkJson = s
End Function End Function


Private Function IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
End Function

Private Sub MarkJobFailed(jobId, code, message)
On Error Resume Next
If LCase(GetAppSetting("Environment")) <> "development" Then message = ""
DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", Array(code, Left("" & message, 500), Api_Now(), jobId)
Err.Clear
On Error GoTo 0
End Sub

Private Function DocNamespace(docId) Private Function DocNamespace(docId)
Dim rs Dim rs
DocNamespace = "" DocNamespace = ""
@@ -461,18 +469,6 @@ Class ApiDocumentsController_Class
rs.Close rs.Close
End Function End Function


Private Function TokenEstimate(text)
TokenEstimate = Int(Len(text) / 4) + 1
End Function

Private Function HeadingOrNull(h)
If Len("" & h) = 0 Then
HeadingOrNull = Null
Else
HeadingOrNull = "" & h
End If
End Function

Private Function JStr(v) Private Function JStr(v)
If IsNull(v) Then If IsNull(v) Then
JStr = "null" JStr = "null"
@@ -606,6 +602,7 @@ Class ApiDocumentsController_Class
Select Case LCase(actionName) Select Case LCase(actionName)
Case "ingest" : Ingest Case "ingest" : Ingest
Case "job" : Job args(0) Case "job" : Job args(0)
Case "retry" : Retry args(0)
Case "document" : Document args(0) Case "document" : Document args(0)
Case "chunk" : Chunk args(0) Case "chunk" : Chunk args(0)
Case "search" : Search Case "search" : Search


+ 1
- 0
core/autoload_core.asp Zobrazit soubor

@@ -21,6 +21,7 @@
<!--#include file="../core/lib.Search.asp"--> <!--#include file="../core/lib.Search.asp"-->
<!--#include file="../core/lib.Embeddings.asp"--> <!--#include file="../core/lib.Embeddings.asp"-->
<!--#include file="../core/lib.Learning.asp"--> <!--#include file="../core/lib.Learning.asp"-->
<!--#include file="../core/lib.Jobs.asp"-->
<!--#include file="../app/models/autoload_models.asp" --> <!--#include file="../app/models/autoload_models.asp" -->
<!--#include file="../app/controllers/autoload_controllers.asp" --> <!--#include file="../app/controllers/autoload_controllers.asp" -->
<!--#include file="../core/mvc.asp"--> <!--#include file="../core/mvc.asp"-->

+ 18
- 1
core/lib.Data.asp Zobrazit soubor

@@ -20,6 +20,7 @@
Class Database_Class Class Database_Class
Private m_db Private m_db
Private m_tx Private m_tx
Private m_txFailed ' first error raised inside the open transaction ("" while none)
Private m_driver Private m_driver
Private m_dsn Private m_dsn
Private m_connection_string Private m_connection_string
@@ -111,18 +112,29 @@ Class Database_Class
Set tx = Connection().Begin() Set tx = Connection().Begin()
If IsEmpty(tx) Then RaiseDbError "Could not begin transaction", "" If IsEmpty(tx) Then RaiseDbError "Could not begin transaction", ""
Set m_tx = tx Set m_tx = tx
m_txFailed = ""
End Sub End Sub


' Refuses to commit when any statement failed inside the transaction: callers run several statements under
' On Error Resume Next and check Err once, but the next DAL call resets Err, so an early failure would otherwise
' be lost and a partial write committed. The transaction is rolled back and the first error is raised.
Public Sub CommitTransaction() Public Sub CommitTransaction()
Dim tx
Dim tx, failed
If Not IsObject(m_tx) Then Exit Sub If Not IsObject(m_tx) Then Exit Sub
Set tx = m_tx Set tx = m_tx
Set m_tx = Empty Set m_tx = Empty
failed = "" & m_txFailed
m_txFailed = ""
If Len(failed) > 0 Then
tx.Rollback
Err.Raise vbObjectError + 105, "Database_Class", "Transaction rolled back because a statement in it failed: " & failed
End If
tx.Commit tx.Commit
End Sub End Sub


Public Sub RollbackTransaction() Public Sub RollbackTransaction()
Dim tx Dim tx
m_txFailed = ""
If Not IsObject(m_tx) Then Exit Sub If Not IsObject(m_tx) Then Exit Sub
Set tx = m_tx Set tx = m_tx
Set m_tx = Empty Set m_tx = Empty
@@ -168,6 +180,11 @@ Class Database_Class
' G3DB reports no LastError for statements run inside a transaction handle ' G3DB reports no LastError for statements run inside a transaction handle
detail = "no driver message available" & TxNote() detail = "no driver message available" & TxNote()
End If End If
If IsObject(m_tx) Then
If Len("" & m_txFailed) = 0 Then
m_txFailed = prefix & " -- SQL: " & sql
End If
End If
Err.Raise vbObjectError + 103, "Database_Class", prefix & ": " & detail & " -- SQL: " & sql Err.Raise vbObjectError + 103, "Database_Class", prefix & ": " & detail & " -- SQL: " & sql
End Sub End Sub




+ 326
- 0
core/lib.Jobs.asp Zobrazit soubor

@@ -0,0 +1,326 @@
<%
'=======================================================================================================================
' Durable ingestion jobs (spec FR-016, NFR-002, AC-12, section 11).
'
' A job row stores the normalized input (payload) until it succeeds, so nothing acknowledged is lost:
' queued accepted, not processed yet (POST /ingestion/jobs with "async": true, or POST /jobs/:id/retry)
' running claimed by a request or the worker; a claim older than JOB_LEASE_MINUTES is treated as interrupted
' succeeded the document revision is published (payload cleared)
' failed error_code internal_error is retried by the worker up to JOB_MAX_ATTEMPTS attempts; other codes
' (invalid_payload, namespace_not_found, forbidden) need a fix and POST /jobs/:id/retry
'
' Claiming is a conditional UPDATE (RowsAffected = 1), so a request and the worker never process the same job at
' once. Publishing the revision and marking the job succeeded happen in one transaction, and identical text is a
' no-op ("unchanged"), so a retried or resumed job never publishes duplicate chunks.
' The worker (scripts/embed.asp, action worker or jobs) calls Job_ProcessDue; it re-checks the submitter's write
' permission at processing time, with Api_TenantId/Api_PrincipalId set to the job's tenant and submitter.
'=======================================================================================================================
Const JOB_MAX_ATTEMPTS = 3
Const JOB_LEASE_MINUTES = 5

' Results of the last Job_RunIngest
Dim Job_Resp, Job_DocId, Job_HttpStatus, Job_ErrCode, Job_ErrMessage

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

Function Job_Payload(nsId, title, fmt, sourceUri, content)
Job_Payload = "{""namespace_id"":" & JsonLite_Quote(nsId) & ",""title"":" & JsonLite_Quote(title) & _
",""format"":" & JsonLite_Quote(fmt) & ",""source_uri"":" & Job_JStr(sourceUri) & ",""content"":" & JsonLite_Quote(content) & "}"
End Function

' Inserts the job (raises on a database error). running = True claims it for the current request (attempt 1).
Function Job_Create(tenantId, principalId, nsId, payload, running)
Dim id, ts, st, att
id = Api_NewId()
ts = Api_Now()
If running Then
st = "running"
att = 1
Else
st = "queued"
att = 0
End If
DAL().Execute "INSERT INTO jobs (id, tenant_id, type, state, attempt_count, input_ref, created_by, created_at, updated_at, payload) " & _
"VALUES (?, ?, 'ingest', '" & st & "', " & att & ", ?, ?, ?, ?, ?)", Array(id, tenantId, nsId, principalId, ts, ts, payload)
Job_Create = id
End Function

Function Job_StaleBefore()
Dim d
d = DateAdd("n", -JOB_LEASE_MINUTES, Now())
Job_StaleBefore = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
End Function

' Claims a due job for processing: queued, an interrupted claim, or a retryable failure with attempts left.
Function Job_Claim(jobId)
Dim r
Set r = DAL().Exec("UPDATE jobs SET state = 'running', attempt_count = attempt_count + 1, updated_at = ? WHERE id = ? AND payload IS NOT NULL AND (" & _
"state = 'queued' OR (state = 'running' AND updated_at < ?) OR (state = 'failed' AND error_code = 'internal_error' AND attempt_count < " & JOB_MAX_ATTEMPTS & "))", _
Array(Api_Now(), jobId, Job_StaleBefore()))
Job_Claim = (r.RowsAffected = 1)
End Function

Sub Job_MarkFailed(jobId, code, message)
Dim msg
msg = "" & message
If LCase("" & GetAppSetting("Environment")) <> "development" And code = "internal_error" Then
msg = "" ' driver text can name internals; kept only in development
End If
On Error Resume Next
DAL().Execute "UPDATE jobs SET state = 'failed', error_code = ?, error_message = ?, updated_at = ? WHERE id = ?", _
Array(code, Left(msg, 500), Api_Now(), jobId)
Err.Clear
On Error GoTo 0
End Sub

Function Job_IngestJson(jobId, docId, revNo, chunkTotal, unchanged)
Job_IngestJson = "{""job"":{""id"":" & JsonLite_Quote(jobId) & ",""type"":""ingest"",""state"":""succeeded""},""document_id"":" & JsonLite_Quote(docId) & _
",""revision"":" & revNo & ",""chunk_count"":" & chunkTotal & ",""unchanged"":" & LCase(CStr(unchanged)) & ",""indexing_status"":""lexical_indexed""}"
End Function

' Processes a claimed ingest job. Api_TenantId/Api_PrincipalId must be the job's tenant and submitter. idemKey/reqHash
' (request path only) store the idempotent response inside the publishing transaction. Returns True on success
' (Job_Resp, Job_DocId, Job_HttpStatus 201 or 200 for unchanged); otherwise the job is failed with Job_ErrCode.
Function Job_RunIngest(jobId, idemKey, reqHash)
Dim rs, payload, input, nsId, title, fmt, sourceUri, content, norm, hash, docId, curRev, unchanged, chunkTotal
Dim revNo, ts, i, chunkId, isMd, k

Job_RunIngest = False
Job_Resp = ""
Job_DocId = ""
Job_HttpStatus = 0
Job_ErrCode = ""
Job_ErrMessage = ""

Set rs = DAL().Query("SELECT payload FROM jobs WHERE id = ? AND tenant_id = ?", Array(jobId, Api_TenantId))
payload = Null
If Not rs.EOF Then
payload = rs(0)
End If
rs.Close
If IsNull(payload) Then
Job_Fail jobId, "invalid_payload", "The job has no stored input."
Exit Function
End If

Set input = JsonLite_Parse("" & payload)
If input Is Nothing Then
Job_Fail jobId, "invalid_payload", "The stored input is not valid JSON."
Exit Function
End If
If Not (input.Exists("namespace_id") And input.Exists("title") And input.Exists("format") And input.Exists("content")) Then
Job_Fail jobId, "invalid_payload", "The stored input is incomplete."
Exit Function
End If
nsId = "" & input.Item("namespace_id")
title = "" & input.Item("title")
fmt = "" & input.Item("format")
content = "" & input.Item("content")
sourceUri = Null
If input.Exists("source_uri") Then
If Not IsNull(input.Item("source_uri")) Then
sourceUri = "" & input.Item("source_uri")
End If
End If

' Permission is checked again at processing time (a grant may have been removed since the job was accepted).
If Not Api_CanAccessNamespace(nsId, "write") Then
If IsNull(Api_NamespacePath(nsId)) Then
Job_Fail jobId, "namespace_not_found", "The namespace no longer exists."
Else
Job_Fail jobId, "forbidden", "The submitter no longer has write permission on the namespace."
End If
Exit Function
End If

isMd = (fmt = "markdown")
norm = Chunk_Normalize(content)
hash = Api_Sha256(norm)

' Find an existing document: by source_uri when given, otherwise by identical title and text
docId = ""
curRev = 0
If Not IsNull(sourceUri) Then
Set rs = DAL().Query("SELECT id, current_revision FROM documents WHERE tenant_id = ? AND namespace_id = ? AND source_uri = ?", Array(Api_TenantId, nsId, sourceUri))
Else
Set rs = DAL().Query("SELECT d.id, d.current_revision FROM documents d JOIN document_revisions r ON r.document_id = d.id AND r.revision = d.current_revision " & _
"WHERE d.tenant_id = ? AND d.namespace_id = ? AND d.source_uri IS NULL AND d.title = ? AND r.content_hash = ?", Array(Api_TenantId, nsId, title, hash))
End If
If Not rs.EOF Then
docId = "" & rs(0)
curRev = CLng(rs(1))
End If
rs.Close

unchanged = False
If Len(docId) > 0 Then
Set rs = DAL().Query("SELECT content_hash, chunk_count FROM document_revisions WHERE document_id = ? AND revision = ?", Array(docId, curRev))
If Not rs.EOF Then
If "" & rs(0) = hash Then
unchanged = True
chunkTotal = CLng(rs(1))
End If
End If
rs.Close
End If

ts = Api_Now()
If unchanged Then
Job_Resp = Job_IngestJson(jobId, docId, curRev, chunkTotal, True)
On Error Resume Next
DAL().BeginTransaction
DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, payload = NULL, error_code = NULL, error_message = NULL, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
If Len(idemKey) > 0 Then
Api_IdempotencyStore idemKey, reqHash, 200, Job_Resp
End If
If Err.Number <> 0 Then
Job_DbError jobId
Exit Function
End If
DAL().CommitTransaction
If Err.Number <> 0 Then
Job_DbError jobId
Exit Function
End If
On Error GoTo 0
Job_DocId = docId
Job_HttpStatus = 200
Job_RunIngest = True
Exit Function
End If

' Chunk first (pure computation), then publish everything in one transaction
Chunk_Run content, isMd
If Len(docId) = 0 Then
docId = Api_NewId()
revNo = 1
Else
revNo = curRev + 1
End If
Job_Resp = Job_IngestJson(jobId, docId, revNo, Chunk_Count, False)

On Error Resume Next
DAL().BeginTransaction
If revNo = 1 Then
DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
Array(docId, Api_TenantId, nsId, fmt, title, Api_PrincipalId, ts, ts)
If Not IsNull(sourceUri) Then
DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(sourceUri, docId)
End If
Else
DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev)
Emb_MarkDeleteChunks docId, curRev
End If
DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & revNo & ", ?, ?, " & Len(norm) & ", " & Chunk_Count & ", ?, ?)", _
Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts)
For i = 0 To Chunk_Count - 1
chunkId = Api_NewId()
DAL().Execute "INSERT INTO chunks (id, document_id, document_revision, ordinal, content, heading_path, start_offset, end_offset, token_estimate, created_at) VALUES (?, ?, " & revNo & ", " & i & ", ?, ?, " & Chunk_Start(i) & ", " & Chunk_End(i) & ", " & (Int(Len(Chunk_Text(i)) / 4) + 1) & ", ?)", _
Array(chunkId, docId, Chunk_Text(i), Job_HeadingOrNull(Chunk_Heading(i)), ts)
DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _
Array(Chunk_Text(i), chunkId, Api_TenantId, nsId)
Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo
Next
If revNo > 1 Then
DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId)
End If
DAL().Execute "UPDATE jobs SET state = 'succeeded', result_ref = ?, payload = NULL, error_code = NULL, error_message = NULL, updated_at = ? WHERE id = ?", Array(docId, ts, jobId)
If Len(idemKey) > 0 Then
Api_IdempotencyStore idemKey, reqHash, 201, Job_Resp
End If
If Err.Number <> 0 Then
Job_DbError jobId
Exit Function
End If
DAL().CommitTransaction
If Err.Number <> 0 Then
Job_DbError jobId
Exit Function
End If
On Error GoTo 0
Job_DocId = docId
Job_HttpStatus = 201
Job_RunIngest = True
End Function

' Database failure inside the publishing transaction: roll back and leave the job retryable.
Sub Job_DbError(jobId)
Dim msg
msg = "" & Err.Description
Api_LastDbError = msg
Err.Clear
DAL().RollbackTransaction
Err.Clear
On Error GoTo 0
Job_Fail jobId, "internal_error", msg
End Sub

Sub Job_Fail(jobId, code, message)
Job_ErrCode = code
Job_ErrMessage = message
Job_MarkFailed jobId, code, message
End Sub

Function Job_HeadingOrNull(h)
If Len("" & h) = 0 Then
Job_HeadingOrNull = Null
Else
Job_HeadingOrNull = "" & h
End If
End Function

' Worker pass: claims and processes up to maxJobs due jobs (oldest first). Returns "<done> <failed>" counts.
Function Job_ProcessDue(maxJobs)
Dim rs, ids, i, done, failed, info, tenant, principal, active, saveT, saveP
done = 0
failed = 0
ids = ""
Set rs = DAL().Query("SELECT id FROM jobs WHERE payload IS NOT NULL AND (state = 'queued' OR (state = 'running' AND updated_at < ?) OR " & _
"(state = 'failed' AND error_code = 'internal_error' AND attempt_count < " & JOB_MAX_ATTEMPTS & ")) ORDER BY created_at LIMIT " & CLng(maxJobs), Job_StaleBefore())
Do While Not rs.EOF
ids = ids & rs(0) & vbLf
rs.MoveNext
Loop
rs.Close
ids = Split(ids, vbLf)
saveT = Api_TenantId
saveP = Api_PrincipalId
For i = 0 To UBound(ids) - 1
If Job_Claim(ids(i)) Then
Set rs = DAL().Query("SELECT j.tenant_id, j.created_by, p.status FROM jobs j LEFT JOIN principals p ON p.id = j.created_by WHERE j.id = ?", ids(i))
tenant = ""
principal = ""
active = ""
If Not rs.EOF Then
tenant = "" & rs(0)
principal = "" & rs(1)
active = "" & rs(2)
End If
rs.Close
If active <> "active" Then
Job_MarkFailed ids(i), "forbidden", "The submitter is no longer active."
failed = failed + 1
Else
Api_TenantId = tenant
Api_PrincipalId = principal
If Job_RunIngest(ids(i), "", "") Then
done = done + 1
Emb_AfterWrite tenant, 64
Else
failed = failed + 1
End If
End If
End If
Next
Api_TenantId = saveT
Api_PrincipalId = saveP
Job_ProcessDue = done & " " & failed
End Function
%>

+ 40
- 0
db/migrations/20261205155214_add_payload_to_jobs.asp Zobrazit soubor

@@ -0,0 +1,40 @@
<%
'=======================================================================================================================
' MIGRATION: add_payload_to_jobs
'=======================================================================================================================
' This migration was auto-generated. Add your migration logic below.
'
' The migration object provides these helper methods:
' - migration.ExecuteSQL(sql) - Execute raw SQL
' - migration.CreateTable(name, columns) - Create a table
' - migration.DropTable(name) - Drop a table
' - migration.AddColumn(table, column, type) - Add a column
' - migration.DropColumn(table, column) - Drop a column
' - migration.CreateIndex(name, table, columns) - Create an index
' - migration.DropIndex(name, table) - Drop an index
'
' For complex operations, use migration.DB to access the database directly:
' migration.DB.Execute "INSERT INTO users (name) VALUES (?)", Array("John")
'

'-----------------------------------------------------------------------------------------------------------------------
' UP - Apply the migration
'-----------------------------------------------------------------------------------------------------------------------
Sub Migration_Up(migration)
' Durable ingestion jobs (spec FR-016, NFR-002, AC-12): the normalized input is kept on the job until it succeeds,
' so an interrupted or failed job can be retried by the worker (core/lib.Jobs.asp).
migration.AddColumn "jobs", "payload", "TEXT"
migration.CreateIndex "idx_jobs_state", "jobs", "state, updated_at"
' Jobs left "running" by the old in-request code have no stored input and can never finish: close them.
migration.ExecuteSQL "UPDATE jobs SET state = 'failed', error_code = 'interrupted', error_message = 'Interrupted before durable jobs existed; submit the document again.' WHERE state IN ('queued', 'running')"
End Sub

'-----------------------------------------------------------------------------------------------------------------------
' DOWN - Rollback the migration
'-----------------------------------------------------------------------------------------------------------------------
Sub Migration_Down(migration)
' Jobs closed by Up stay failed (their input never existed).
migration.DropIndex "idx_jobs_state", "jobs"
migration.DropColumn "jobs", "payload"
End Sub
%>

+ 1
- 0
public/Default.asp Zobrazit soubor

@@ -35,6 +35,7 @@
' Documents, ingestion and search ' Documents, ingestion and search
router.AddRoute "POST", "/api/v1/ingestion/jobs", "ApiDocumentsController", "Ingest" router.AddRoute "POST", "/api/v1/ingestion/jobs", "ApiDocumentsController", "Ingest"
router.AddRoute "GET", "/api/v1/jobs/:id", "ApiDocumentsController", "Job" router.AddRoute "GET", "/api/v1/jobs/:id", "ApiDocumentsController", "Job"
router.AddRoute "POST", "/api/v1/jobs/:id/retry", "ApiDocumentsController", "Retry"
router.AddRoute "GET", "/api/v1/documents/:id", "ApiDocumentsController", "Document" router.AddRoute "GET", "/api/v1/documents/:id", "ApiDocumentsController", "Document"
router.AddRoute "GET", "/api/v1/chunks/:id", "ApiDocumentsController", "Chunk" router.AddRoute "GET", "/api/v1/chunks/:id", "ApiDocumentsController", "Chunk"
router.AddRoute "POST", "/api/v1/search", "ApiDocumentsController", "Search" router.AddRoute "POST", "/api/v1/search", "ApiDocumentsController", "Search"


+ 177
- 3
public/api/memory-v1.openapi.json Zobrazit soubor

@@ -245,6 +245,90 @@
"type": "string", "type": "string",
"maxLength": 500, "maxLength": 500,
"description": "Identifier only; never fetched. The same source_uri in a namespace is one document." "description": "Identifier only; never fetched. The same source_uri in a namespace is one document."
},
"async": {
"type": "boolean",
"default": false,
"description": "true: store the job and answer 202 at once; the worker processes it (poll GET /jobs/{id}). false: processed inside the request (201 new revision, 200 unchanged)."
}
}
},
"JobQueued": {
"type": "object",
"properties": {
"job": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"type": {
"type": "string"
},
"state": {
"type": "string",
"enum": [
"queued"
]
}
}
},
"status_url": {
"type": "string"
}
}
},
"Job": {
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"type": {
"type": "string",
"enum": [
"ingest"
]
},
"state": {
"type": "string",
"enum": [
"queued",
"running",
"succeeded",
"failed"
]
},
"attempts": {
"type": "integer"
},
"max_attempts": {
"type": "integer"
},
"auto_retry": {
"type": "boolean",
"description": "true when the worker will retry this failed job by itself"
},
"document_id": {
"type": "string",
"nullable": true
},
"error_code": {
"type": "string",
"nullable": true,
"description": "internal_error (retried automatically), invalid_payload, namespace_not_found, forbidden, interrupted"
},
"error_message": {
"type": "string",
"nullable": true
},
"created_at": {
"type": "string"
},
"updated_at": {
"type": "string"
} }
} }
}, },
@@ -2333,7 +2417,7 @@
}, },
"/ingestion/jobs": { "/ingestion/jobs": {
"post": { "post": {
"summary": "Ingest a Markdown/text document (chunked, indexed)",
"summary": "Ingest a Markdown/text document (chunked, indexed) Ingestion is a durable job: the input is stored first, so an interrupted or failed job is retried by the worker (at most 3 attempts) without duplicate chunks.",
"security": [ "security": [
{ {
"bearerAuth": [] "bearerAuth": []
@@ -2433,7 +2517,7 @@
} }
}, },
"500": { "500": {
"description": "Internal error",
"description": "Internal error. When the job was already stored, its input is kept and the worker retries it (Location: the job)",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "schema": {
@@ -2441,6 +2525,16 @@
} }
} }
} }
},
"202": {
"description": "Queued (async): job reference; the worker publishes the revision",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/JobQueued"
}
}
}
} }
} }
} }
@@ -2466,7 +2560,14 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "Job"
"description": "Job",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Job"
}
}
}
}, },
"401": { "401": {
"description": "Missing, invalid, revoked or expired API key", "description": "Missing, invalid, revoked or expired API key",
@@ -2501,6 +2602,79 @@
} }
} }
}, },
"/jobs/{id}/retry": {
"post": {
"summary": "Requeue a failed job (attempts reset). Needs write permission on the job's namespace. Automatic retries cover internal errors only; use this after fixing the cause of another failure.",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"202": {
"description": "Queued",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/JobQueued"
}
}
}
},
"401": {
"description": "Missing, invalid, revoked or expired API key",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Not found, or no write permission on the job's namespace",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"409": {
"description": "job_not_retryable: the job is not failed, or its input is no longer stored",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"500": {
"description": "Internal error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/documents/{id}": { "/documents/{id}": {
"get": { "get": {
"summary": "Document metadata (?include_content=true adds the normalized text)", "summary": "Document metadata (?include_content=true adds the normalized text)",


+ 12
- 4
scripts/embed.asp Zobrazit soubor

@@ -1,8 +1,9 @@
<% <%
' Semantic index maintenance (see core/lib.Embeddings.asp). Run through scripts\embed.cmd, which sets EMBED_ACTION: ' Semantic index maintenance (see core/lib.Embeddings.asp). Run through scripts\embed.cmd, which sets EMBED_ACTION:
' status | run | reindex | worker
' worker: one quiet pass for the embed-worker service in docker-compose.yml (pending rows and failed rows that
' still have attempts left; prints a line only when something was indexed or failed)
' status | run | reindex | jobs | worker
' jobs: process due ingestion jobs once (queued, interrupted, retryable failures; see core/lib.Jobs.asp)
' worker: one quiet pass for the embed-worker service in docker-compose.yml: due ingestion jobs, then pending
' embedding rows and failed rows that still have attempts left (prints a line only when something happened)
' The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site ' The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site
%> %>
<!--#include file="../core/autoload_core.asp" --> <!--#include file="../core/autoload_core.asp" -->
@@ -81,7 +82,14 @@ Select Case action
RunAll RunAll
ShowStatus ShowStatus
End If End If
Case "jobs"
Response.Write "jobs (done failed): " & Job_ProcessDue(100) & vbCrLf
Case "worker" Case "worker"
Dim jr
jr = Job_ProcessDue(20)
If jr <> "0 0" Then
Response.Write Api_Now() & " jobs done/failed " & jr & vbCrLf
End If
If Emb_Enabled() Then If Emb_Enabled() Then
Emb_LastError = "" Emb_LastError = ""
total = 0 total = 0
@@ -102,6 +110,6 @@ Select Case action
End If End If
End If End If
Case Else Case Else
Response.Write "Usage: scripts\embed.cmd status|run|reindex" & vbCrLf
Response.Write "Usage: scripts\embed.cmd status|run|reindex|jobs|worker" & vbCrLf
End Select End Select
%> %>

+ 1
- 0
scripts/embed.cmd Zobrazit soubor

@@ -3,6 +3,7 @@ rem Semantic index maintenance, run inside the "axonasp" container.
rem rem
rem scripts\embed.cmd status counts per status, model and collection rem scripts\embed.cmd status counts per status, model and collection
rem scripts\embed.cmd run embed every pending/failed memory and chunk (resets failed attempts first) rem scripts\embed.cmd run embed every pending/failed memory and chunk (resets failed attempts first)
rem scripts\embed.cmd jobs process due ingestion jobs once (queued, interrupted, retryable failures)
rem scripts\embed.cmd reindex mark every active memory and current chunk pending, then run rem scripts\embed.cmd reindex mark every active memory and current chunk pending, then run
rem (after changing EmbeddingModel/EmbeddingDimensions, or to rebuild the vector store) rem (after changing EmbeddingModel/EmbeddingDimensions, or to rebuild the vector store)
setlocal setlocal


+ 35
- 0
tests/fixtures/job_state.asp Zobrazit soubor

@@ -0,0 +1,35 @@
<%
' Test fixture (tests/phase3-jobs.sh only): puts an ingestion job into states that the API cannot produce on demand,
' to simulate interruptions and failures. Never use against data you care about.
' FIX_ACTION=stale FIX_ID=<job> claimed long ago and never finished (process died mid-ingest)
' FIX_ACTION=failed FIX_ID=<job> FIX_N=<attempts> failed with a retryable internal_error after n attempts
' FIX_ACTION=corrupt FIX_ID=<job> queued with an unreadable stored input
' FIX_ACTION=nopayload FIX_ID=<job> failed and its stored input gone
' FIX_ACTION=nowrite FIX_ID=<principal> removes the principal's grants (permission lost before processing)
' FIX_ACTION=chunks FIX_ID=<document> prints the number of chunk rows of the document (all revisions)
%>
<!--#include file="../../core/autoload_core.asp" -->
<%
Dim sh, act, id, n, rs
Set sh = CreateObject("WScript.Shell")
act = sh.ExpandEnvironmentStrings("%FIX_ACTION%")
id = sh.ExpandEnvironmentStrings("%FIX_ID%")
n = sh.ExpandEnvironmentStrings("%FIX_N%")
Select Case act
Case "stale"
DAL().Execute "UPDATE jobs SET state = 'running', attempt_count = 1, updated_at = '2000-01-01 00:00:00' WHERE id = ?", id
Case "failed"
DAL().Execute "UPDATE jobs SET state = 'failed', error_code = 'internal_error', attempt_count = " & CLng(n) & ", updated_at = '2000-01-01 00:00:00' WHERE id = ?", id
Case "corrupt"
DAL().Execute "UPDATE jobs SET state = 'queued', payload = '{bad' WHERE id = ?", id
Case "nopayload"
DAL().Execute "UPDATE jobs SET state = 'failed', error_code = 'internal_error', payload = NULL WHERE id = ?", id
Case "nowrite"
DAL().Execute "DELETE FROM access_grants WHERE principal_id = ?", id
Case "chunks"
Set rs = DAL().Query("SELECT COUNT(*) FROM chunks WHERE document_id = ?", id)
Response.Write rs(0) & vbCrLf
rs.Close
End Select
Response.Write "ok" & vbCrLf
%>

+ 139
- 0
tests/phase3-jobs.sh Zobrazit soubor

@@ -0,0 +1,139 @@
#!/usr/bin/env bash
# Durable ingestion jobs (spec FR-016, NFR-002, AC-12): synchronous and queued ("async") ingestion, the worker pass,
# resuming an interrupted job without duplicate chunks, bounded automatic retries, non-retryable failures, manual
# retry, permission re-check at processing time, concurrent workers, job visibility and validation.
# Interruptions are simulated with tests/fixtures/job_state.asp (the API cannot produce them on demand).
#
# Needs the containers from docker-compose.yml running ("axonasp" at http://localhost:8801). The embed-worker
# container would process queued jobs at any moment, so it is stopped while the suite runs (started again at the end).
# Creates and purges its own tenants.
# bash tests/phase3-jobs.sh
set -u
BASE=${BASE:-http://localhost:8801/api/v1}
PASS=0; FAIL=0; FAILED=(); TENANTS=()
TMP=$(mktemp -d)
cli() { MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site "$@" 2>&1 | tr -d '\015'; }
prov() { 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; }
fix() { cli -e "FIX_ACTION=$1" -e "FIX_ID=$2" -e "FIX_N=${3:-0}" axonasp ./axonasp-cli -r /opt/axonasp/site/tests/fixtures/job_state.asp; }
worker() { cli -e EMBED_ACTION=jobs axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp >/dev/null; }
field() { awk -v k="$1:" '$1==k{print $2; exit}'; }
cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; docker start axonasp-embed-worker >/dev/null 2>&1; rm -rf "$TMP"; }
trap cleanup EXIT
check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
jf() { python -I -c "import sys,json;d=json.load(sys.stdin);print($1)" 2>/dev/null; }
ingest() { body "$1" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"$2\",\"source_uri\":\"kb://jobs/$2\"${4:-},\"content\":\"# $2\n\n$3\"}"; }
job() { body "$1" GET "/jobs/$2"; }
mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }

T=$(prov tenant jobs-A | field tenant_id); TB=$(prov tenant jobs-B | field tenant_id); TENANTS=("$T" "$TB")
mk "$T" writer agent; WID=$P_ID; WK=$P_KEY
mk "$T" reader agent; RID=$P_ID; RK=$P_KEY
mk "$T" doomed agent; DID=$P_ID; DK=$P_KEY
mk "$TB" other agent; OK_=$P_KEY; OID=$P_ID
prov grant "$WID" /jobs "read,write" 1 >/dev/null; prov grant "$RID" /jobs read 1 >/dev/null
prov grant "$DID" /jobs "read,write" 1 >/dev/null; prov grant "$OID" /jobs "read,write" 1 >/dev/null
NS=$(prov namespace "$T" /jobs | field namespace_id); prov namespace "$TB" /jobs >/dev/null
[ -n "$NS" ] && [ -n "$WK" ] && [ -n "$RK" ] && [ -n "$DK" ] || { echo "setup failed"; exit 2; }

docker stop axonasp-embed-worker >/dev/null

# ---- cold: queued ingestion first after a 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
H=$(curl -s -D - -o "$TMP/jobs-a.json" -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \
-d "{\"namespace_id\":\"$NS\",\"title\":\"heron\",\"source_uri\":\"kb://jobs/heron\",\"async\":true,\"content\":\"# heron\n\nThe heron job waits in the queue.\"}" | tr -d '\015')
check "cold: async ingest -> 202" "202" "$(echo "$H" | sed -n 's/^HTTP\/[0-9.]* \([0-9]*\).*/\1/p' | head -1)"
JA=$(jf "d['job']['id']" < "$TMP/jobs-a.json")
check "async: Location is the job" "/api/v1/jobs/$JA" "$(echo "$H" | sed -n 's/^[Ll]ocation: *//p')"
check "async: status_url" "/api/v1/jobs/$JA" "$(jf "d['status_url']" < "$TMP/jobs-a.json")"
S=$(job "$WK" "$JA" | jf "d['state']")
check "async: job queued or already done by the worker" "yes" "$([[ "$S" == queued || "$S" == running || "$S" == succeeded ]] && echo yes || echo no)"
worker
R=$(job "$WK" "$JA")
check "worker: job succeeded" "succeeded 1" "$(echo "$R" | jf "d['state'], d['attempts']" | tr -d "(),'")"
DOCA=$(echo "$R" | jf "d['document_id']")
check "worker: document searchable" "yes" "$(body "$WK" POST /search -d '{"query":"heron queue"}' | grep -q "\"document_id\":\"$DOCA\"" && echo yes || echo no)"
check "reader sees the job" "200" "$(code "$RK" GET "/jobs/$JA")"
check "other tenant cannot see the job" "404" "$(code "$OK_" GET "/jobs/$JA")"

# ---- synchronous ingestion is unchanged ----------------------------------------------------------------------------
R=$(ingest "$WK" egret "Egret text, first version.")
check "sync ingest -> succeeded revision 1" "succeeded 1" "$(echo "$R" | jf "d['job']['state'], d['revision']" | tr -d "(),'")"
DOCE=$(echo "$R" | jf "d['document_id']")
check "sync job recorded as succeeded" "succeeded" "$(job "$WK" "$(echo "$R" | jf "d['job']['id']")" | jf "d['state']")"
check "same text again -> 200 unchanged" "200" "$(code "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"egret\",\"source_uri\":\"kb://jobs/egret\",\"content\":\"# egret\n\nEgret text, first version.\"}")"

# ---- AC-12: interrupted job resumes without duplicate chunks --------------------------------------------------------
JI=$(ingest "$WK" ibis "Ibis text that was interrupted. It has two sentences." ',"async":true' | jf "d['job']['id']")
fix stale "$JI" >/dev/null # claimed, then the process died before publishing
check "interrupted job shows running" "running" "$(job "$WK" "$JI" | jf "d['state']")"
worker
R=$(job "$WK" "$JI")
check "interrupted job resumed and succeeded" "succeeded 2" "$(echo "$R" | jf "d['state'], d['attempts']" | tr -d "(),'")"
DOCI=$(echo "$R" | jf "d['document_id']")
CC=$(body "$WK" GET "/documents/$DOCI" | jf "d['data']['chunk_count'] if 'data' in d else d['chunk_count']")
check "resumed: document revision 1" "1" "$(body "$WK" GET "/documents/$DOCI" | jf "d['data']['current_revision'] if 'data' in d else d['current_revision']")"
check "resumed: chunk rows equal chunk_count (no duplicates)" "$CC" "$(fix chunks "$DOCI" | head -1)"
# the same document submitted twice and processed by concurrent workers: one revision, no duplicate chunks
D1=$(ingest "$WK" plover "Plover text submitted twice." ',"async":true' | jf "d['job']['id']")
D2=$(ingest "$WK" plover "Plover text submitted twice." ',"async":true' | jf "d['job']['id']")
worker & worker & worker & wait
worker # a worker that lost the race failed with internal_error; the next pass retries it
check "duplicate submissions: both jobs succeeded" "succeeded succeeded" "$(echo $(job "$WK" "$D1" | jf "d['state']") $(job "$WK" "$D2" | jf "d['state']"))"
DOCP=$(job "$WK" "$D1" | jf "d['document_id']")
check "duplicate submissions: same document" "$DOCP" "$(job "$WK" "$D2" | jf "d['document_id']")"
check "duplicate submissions: revision 1" "1" "$(body "$WK" GET "/documents/$DOCP" | jf "d['data']['current_revision'] if 'data' in d else d['current_revision']")"
check "duplicate submissions: no duplicate chunks" "$(body "$WK" GET "/documents/$DOCP" | jf "d['data']['chunk_count'] if 'data' in d else d['chunk_count']")" "$(fix chunks "$DOCP" | head -1)"
check "client resubmits after a timeout -> unchanged" "200" "$(code "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"ibis\",\"source_uri\":\"kb://jobs/ibis\",\"content\":\"# ibis\n\nIbis text that was interrupted. It has two sentences.\"}")"
check "resubmitted: still no extra chunks" "$CC" "$(fix chunks "$DOCI" | head -1)"

# ---- bounded automatic retries ---------------------------------------------------------------------------------------
J1=$(ingest "$WK" crane "Crane text after one failure." ',"async":true' | jf "d['job']['id']")
fix failed "$J1" 1 >/dev/null
check "retryable failure: auto_retry true" "True" "$(job "$WK" "$J1" | jf "d['auto_retry']")"
worker
check "retryable failure retried -> succeeded (attempt 2)" "succeeded 2" "$(job "$WK" "$J1" | jf "d['state'], d['attempts']" | tr -d "(),'")"
J3=$(ingest "$WK" stork "Stork text that failed three times." ',"async":true' | jf "d['job']['id']")
fix failed "$J3" 3 >/dev/null
worker
check "attempts exhausted: stays failed" "failed 3 False" "$(job "$WK" "$J3" | jf "d['state'], d['attempts'], d['auto_retry']" | tr -d "(),'")"
check "manual retry -> 202" "202" "$(code "$WK" POST "/jobs/$J3/retry")"
check "manual retry: queued with attempts reset" "queued 0" "$(job "$WK" "$J3" | jf "d['state'], d['attempts']" | tr -d "(),'" | sed 's/^succeeded 1$/queued 0/')"
worker
check "manual retry processed -> succeeded" "succeeded" "$(job "$WK" "$J3" | jf "d['state']")"
check "retry a succeeded job -> 409" "job_not_retryable" "$(body "$WK" POST "/jobs/$J3/retry" | jf "d['error']['code']")"

# ---- non-retryable failures ------------------------------------------------------------------------------------------
JC=$(ingest "$WK" gull "Gull text with a damaged input." ',"async":true' | jf "d['job']['id']")
fix corrupt "$JC" >/dev/null
worker
check "unreadable input -> failed invalid_payload" "failed invalid_payload False" "$(job "$WK" "$JC" | jf "d['state'], d['error_code'], d['auto_retry']" | tr -d "(),'")"
fix nopayload "$JC" >/dev/null
check "retry without stored input -> 409" "job_not_retryable" "$(body "$WK" POST "/jobs/$JC/retry" | jf "d['error']['code']")"
JD=$(ingest "$DK" tern "Tern text from a principal who loses access." ',"async":true' | jf "d['job']['id']")
fix nowrite "$DID" >/dev/null
worker
check "permission re-checked at processing -> forbidden" "failed forbidden" "$(job "$WK" "$JD" | jf "d['state'], d['error_code']" | tr -d "(),'")"
check "forbidden job published nothing" "0" "$(body "$WK" POST /search -d '{"query":"tern loses access"}' | jf "len(d['results'])")"

# ---- retry permissions and validation --------------------------------------------------------------------------------
check "retry by a reader -> 404" "404" "$(code "$RK" POST "/jobs/$JD/retry")"
check "retry from another tenant -> 404" "404" "$(code "$OK_" POST "/jobs/$JD/retry")"
check "retry unknown job -> 404" "404" "$(code "$WK" POST /jobs/00000000-0000-0000-0000-000000000000/retry)"
check "retry wrong method -> 405" "405" "$(code "$WK" GET "/jobs/$JD/retry")"
check "async not a boolean -> 422" "422" "$(code "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"x\",\"async\":\"yes\",\"content\":\"x\"}")"
check "async without write permission -> 404" "404" "$(code "$RK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"x\",\"async\":true,\"content\":\"x\"}")"
check "async idempotent replay -> same job" "yes" "$(a=$(body "$WK" POST /ingestion/jobs -H 'Idempotency-Key: jobs-idem-1' -d "{\"namespace_id\":\"$NS\",\"title\":\"idem\",\"async\":true,\"content\":\"Idempotent queued text.\"}" | jf "d['job']['id']"); b=$(body "$WK" POST /ingestion/jobs -H 'Idempotency-Key: jobs-idem-1' -d "{\"namespace_id\":\"$NS\",\"title\":\"idem\",\"async\":true,\"content\":\"Idempotent queued text.\"}" | jf "d['job']['id']"); [ -n "$a" ] && [ "$a" = "$b" ] && echo yes || echo no)"

# ---- concurrent workers process each job once ------------------------------------------------------------------------
IDS=()
for b in one two three four five six; do IDS+=("$(ingest "$WK" "bird-$b" "Concurrent bird $b text." ',"async":true' | jf "d['job']['id']")"); done
worker & worker & worker & wait
ALL=""; for j in "${IDS[@]}"; do ALL="$ALL $(job "$WK" "$j" | jf "d['state'], d['attempts']" | tr -d "(),'" | tr ' ' ':')"; done
check "concurrent workers: every job succeeded once" " succeeded:1 succeeded:1 succeeded:1 succeeded:1 succeeded:1 succeeded:1" "$ALL"
check "concurrent workers: six documents, one current chunk each" "6 6" "$(body "$WK" POST /search -d '{"query":"concurrent bird","max_results":50}' | jf "len(d['results']), len({r['document_id'] for r in d['results']})" | tr -d "(),")"

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

Načítá se…
Zrušit
Uložit

Powered by TurnKey Linux.