Procházet zdrojové kódy

Embeddings: bounded waits inside web requests

On the 2-vCPU production VM a small ingest after a large import hit the 60 s
script timeout: the write committed, but post-commit indexing kept embedding
the tenant's backlog while Ollama was busy, so the client saw an error.

- Provider/store calls in web requests wait at most EmbeddingTimeoutMs (10 s);
  recall/search/context fall back to lexical instead of stalling
- Emb_AfterWrite stops starting batches after EmbeddingWriteBudgetMs (8 s) and
  leaves rows pending (no attempt used) for the embed-worker
- The CLI worker (scripts/embed.asp) still waits up to 60 s per call
- .gitignore: all .amk*.env files (production and local KB settings)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/1/head
Daniel Covington před 10 hodinami
rodič
revize
fb23814c67
6 změnil soubory, kde provedl 59 přidání a 4 odebrání
  1. +1
    -1
      .gitignore
  2. +1
    -0
      AGENTS.md
  3. +50
    -2
      core/lib.Embeddings.asp
  4. +4
    -0
      public/web.config
  5. +1
    -0
      scripts/embed.asp
  6. +2
    -1
      tests/phase3-semantic.sh

+ 1
- 1
.gitignore Zobrazit soubor

@@ -10,7 +10,7 @@
/UPSTREAM-TODO.txt

# Local knowledge base keys (scripts/kb.sh)
/.amk.env
/.amk*.env

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


+ 1
- 0
AGENTS.md Zobrazit soubor

@@ -186,6 +186,7 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o
- **G3DB takes at most 8 parameters per statement** ("Too many parameters (12); the maximum is 8"). Split wide INSERTs into an INSERT plus an UPDATE inside one transaction (see `InsertRevision` in `ApiMemoriesController.asp`).
- **Characters above U+FFFF (emoji) cannot be held** on the pinned build (CLI v2.3.42): `ChrW(128512)` raises "Invalid procedure call" (older builds returned one character), and `ChrW(55357) & ChrW(56832)` is written out as CESU-8 (`ED A0 BD ...`), which is invalid UTF-8. `Api_Utf8Decode` and JsonLite therefore flag such code points (raw 4-byte UTF-8 or escaped surrogate pairs) and `Api_ReadBody` answers 422 `unsupported_character`; the generator template does the same. Do not store them as U+FFFD silently.
- **Calling HTTP services from a request works alongside G3DB** (verified with `MSXML2.ServerXMLHTTP` to Ollama and Qdrant, reads and writes before and after, cold first request). Set `SetTimeouts` so a dead service cannot hang the request, never let an HTTP failure fail a database write, and keep large JSON (vectors) as text: slice it with `InStr`/`Split` instead of parsing it with JsonLite.
- **A busy embedding provider must not stall requests.** On the 2-vCPU production VM, a small ingest right after a 312-chunk import hit the 60 s script timeout. The write had committed, but the post-commit indexing kept embedding the tenant's pending backlog while the worker loaded Ollama, so the client got error 4011 for a successful write. Inside web requests each provider/store call now waits at most `EmbeddingTimeoutMs` (10 s) and `Emb_AfterWrite` stops starting batches after `EmbeddingWriteBudgetMs` (8 s), leaving rows pending without using up attempts. Only the CLI worker waits 60 s. Test slow-provider behaviour with `docker pause ollama` (connections hang) as well as `docker stop ollama` (connections refused).
- **Embedding similarity thresholds are model-specific.** With `nomic-embed-text` (and its `search_query: `/`search_document: ` prefixes) relevant pairs scored 0.61-0.67 and unrelated ones up to 0.58, hence `EmbeddingMinScore` 0.6. Re-measure before changing the model, and remember the memory title is part of the embedded (and FTS-indexed) text.
- **`AscW` is signed:** characters U+8000..U+FFFF give negative values, so `AscW(c) > 127` misses them (fixed in `Search_FtsQuery`). The same applies to `CLng("&H" & hex)` for 4-digit hex.
- **`content_hash` is not a content hash.** `memory_revisions.content_hash` is SHA-256 of `namespace|type|title|content` (used for duplicate detection in one namespace). To dedupe the same text across namespaces compare the content itself (as `ApiContextController` does).


+ 50
- 2
core/lib.Embeddings.asp Zobrazit soubor

@@ -22,6 +22,11 @@
' EmbeddingMinScore cosine similarity below which a semantic hit is ignored (default 0.6; model-specific: for
' nomic-embed-text relevant pairs scored 0.61-0.67, unrelated ones up to 0.58)
' VectorStoreUrl http://qdrant:6333
' EmbeddingTimeoutMs receive timeout per provider/store call inside a web request (default 10000), so a busy
' provider makes recall/search/context fall back to lexical instead of stalling the request.
' scripts/embed.asp (CLI, worker) uses 60000.
' EmbeddingWriteBudgetMs time Emb_AfterWrite may spend indexing after a commit (default 8000): no new batch starts
' after it, and rows it could not index stay pending for the worker (no attempt is used up).
' The Qdrant collection is amk_<model>_<dimensions>, so changing the model starts a new collection (run embed reindex).
' No native object is held across calls: each HTTP call creates and releases its own MSXML2.ServerXMLHTTP.
'=======================================================================================================================
@@ -30,8 +35,37 @@ Const EMB_BATCH = 16
Const EMB_MAX_ATTEMPTS = 5
Const EMB_MAX_TEXT = 8000

Dim Emb_LastError
Dim Emb_LastError, Emb_TimeoutMs, Emb_BudgetMs, Emb_BudgetStart
Emb_LastError = ""
Emb_TimeoutMs = 0 ' 0: EmbeddingTimeoutMs setting; scripts/embed.asp sets 60000
Emb_BudgetMs = 0 ' > 0 only while Emb_AfterWrite runs

Function Emb_CallTimeoutMs()
Dim v
If Emb_TimeoutMs > 0 Then
Emb_CallTimeoutMs = Emb_TimeoutMs
Exit Function
End If
v = Emb_Setting("EmbeddingTimeoutMs", "10000")
If Not IsNumeric(v) Then
v = "10000"
End If
Emb_CallTimeoutMs = CLng(v)
End Function

' True when Emb_AfterWrite's time budget is spent (Timer wraps at midnight).
Function Emb_OverBudget()
Dim d
Emb_OverBudget = False
If Emb_BudgetMs <= 0 Then
Exit Function
End If
d = Timer - Emb_BudgetStart
If d < 0 Then
d = d + 86400
End If
Emb_OverBudget = (d * 1000 >= Emb_BudgetMs)
End Function

Function Emb_Setting(key, dflt)
Dim v
@@ -80,7 +114,7 @@ Function Emb_Http(method, url, body, ByRef status)
status = 0
On Error Resume Next
Set http = Server.CreateObject("MSXML2.ServerXMLHTTP")
http.SetTimeouts 2000, 2000, 10000, 60000
http.SetTimeouts 2000, 2000, 10000, Emb_CallTimeoutMs()
http.Open method, url, False
If Len(body) > 0 Then
http.SetRequestHeader "Content-Type", "application/json"
@@ -204,6 +238,13 @@ Sub Emb_AfterWrite(tenantId, maxItems)
If Not Emb_Enabled() Then
Exit Sub
End If
Dim b
b = Emb_Setting("EmbeddingWriteBudgetMs", "8000")
If Not IsNumeric(b) Then
b = "8000"
End If
Emb_BudgetStart = Timer
Emb_BudgetMs = CLng(b)
On Error Resume Next
n = Emb_ProcessPending(tenantId, maxItems)
If Err.Number <> 0 Then
@@ -211,6 +252,7 @@ Sub Emb_AfterWrite(tenantId, maxItems)
Err.Clear
End If
On Error GoTo 0
Emb_BudgetMs = 0
End Sub

' Processes deletions and up to maxItems pending/failed rows (tenantId "" = all tenants). Returns rows indexed.
@@ -319,6 +361,9 @@ Function Emb_ProcessPending(tenantId, maxItems)
done = 0
batchStart = 0
Do While batchStart < k
If batchStart > 0 And Emb_OverBudget() Then
Exit Do ' request time budget spent: the worker indexes the rest
End If
batchEnd = batchStart + EMB_BATCH - 1
If batchEnd > k - 1 Then
batchEnd = k - 1
@@ -342,6 +387,9 @@ Function Emb_ProcessPending(tenantId, maxItems)
"{""points"":[" & body & "]}", status)
ok = (status = 200)
End If
If Not ok And Emb_BudgetMs > 0 Then
Exit Do ' inside a request: leave the rows pending for the worker, do not use up their attempts
End If
ts = Api_Now()
For j = batchStart To batchEnd
If ok Then


+ 4
- 0
public/web.config Zobrazit soubor

@@ -55,6 +55,10 @@
<add key="EmbeddingQueryPrefix" value="search_query: " />
<add key="EmbeddingMinScore" value="0.6" />
<add key="VectorStoreUrl" value="http://qdrant:6333" />
<!-- Inside web requests: per-call wait for the provider/store, and the time spent indexing after a commit.
Slow hosts fall back to lexical retrieval and leave indexing to the embed-worker instead of timing out. -->
<add key="EmbeddingTimeoutMs" value="10000" />
<add key="EmbeddingWriteBudgetMs" value="8000" />
</appSettings>

<system.webServer>


+ 1
- 0
scripts/embed.asp Zobrazit soubor

@@ -8,6 +8,7 @@
<!--#include file="../core/autoload_core.asp" -->
<%
Dim sh : Set sh = CreateObject("WScript.Shell")
Emb_TimeoutMs = 60000 ' the worker may wait for a slow provider (web requests use EmbeddingTimeoutMs)
Dim action : action = LCase(Trim(sh.ExpandEnvironmentStrings("%EMBED_ACTION%")))
Dim rs, total, n, rounds, ts



+ 2
- 1
tests/phase3-semantic.sh Zobrazit soubor

@@ -111,7 +111,8 @@ check "provider down: remember still 201" "201" "$(code "$WK" POST /remember -d
M4=$(body "$WK" GET "/memories?namespace_id=$NS&limit=50" | python -I -c "import sys,json;print([m['id'] for m in json.load(sys.stdin)['data'] if m['title']=='Pets'][0])")
verify "$WK" "$M4"
check "provider down: new memory not yet embedded" "2" "$(points "$TA" memory)"
check "provider down: status shows failed" "yes" "$(embed status | grep -q 'failed: ' && echo yes || echo no)"
# a web request leaves the row pending (no attempt used); the embed-worker may already have tried it and marked it failed
check "provider down: status shows pending or failed" "yes" "$(embed status | grep -qE '(pending|failed): ' && echo yes || echo no)"
docker start ollama >/dev/null; for i in $(seq 1 30); do docker exec axonasp wget -qO- http://ollama:11434/api/version >/dev/null 2>&1 && break; sleep 1; done
embed run >/dev/null
check "embed run catches up" "3" "$(points "$TA" memory)"


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

Powered by TurnKey Linux.