Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

373 lines
17KB

  1. <%
  2. '=======================================================================================================================
  3. ' Learning loop support (spec FR-012, FR-013, FR-014, FR-020, section 12): evidence links, memory writes shared by
  4. ' remember/correct and candidate review, and retrieval telemetry for feedback (AC-18).
  5. '
  6. ' Evidence : Set ev = New Evidence_Class : msg = ev.Load(input, "evidence") ("" = ok, else a validation message)
  7. ' then, inside the write transaction: ev.Save "memory"|"candidate", ownerId, ownerRevision (or Null)
  8. ' Every target must be in the caller's tenant and readable by the caller; the target revision is
  9. ' pinned at link time (memory/document current revision, chunk document revision).
  10. ' Memories : Mem_InsertRevision, Mem_Create, Mem_Revise (call inside a transaction; they also update the lexical
  11. ' index and mark the semantic index pending; call Emb_AfterWrite after commit)
  12. ' Evidence_Json ownerKind, ownerId, ownerRev: the evidence of an owner as JSON (unreadable targets shown without id)
  13. ' Telemetry : Tel_Record queryId, operation, strategy, queryText, resultsSpec, startTimer
  14. ' resultsSpec = "kind|id|revision|score" items joined by Chr(30). Only a hash of the query is kept.
  15. '=======================================================================================================================
  16. Const EVIDENCE_MAX = 20
  17. Class Evidence_Class
  18. Private m_kind(), m_id(), m_rev(), m_role(), m_excerpt(), m_n
  19. Private Sub Class_Initialize()
  20. m_n = 0
  21. ReDim m_kind(EVIDENCE_MAX)
  22. ReDim m_id(EVIDENCE_MAX)
  23. ReDim m_rev(EVIDENCE_MAX)
  24. ReDim m_role(EVIDENCE_MAX)
  25. ReDim m_excerpt(EVIDENCE_MAX)
  26. End Sub
  27. Public Property Get Count()
  28. Count = m_n
  29. End Property
  30. ' Reads and validates input(name): an optional array of {"kind","id","role","excerpt"}.
  31. Public Function Load(input, name)
  32. Dim items, i, o, kind, id, role, excerpt, rev, ns, rs, pos
  33. Load = ""
  34. m_n = 0
  35. If Not input.HasRaw(name) Then
  36. If input.Exists(name) Then
  37. If Not IsNull(input.Item(name)) Then
  38. Load = name & " must be an array of objects."
  39. End If
  40. End If
  41. Exit Function
  42. End If
  43. items = JsonLite_SplitObjectArray(input.Raw(name))
  44. If IsNull(items) Then
  45. Load = name & " must be an array of objects."
  46. Exit Function
  47. End If
  48. If UBound(items) + 1 > EVIDENCE_MAX Then
  49. Load = name & " may contain at most " & EVIDENCE_MAX & " items."
  50. Exit Function
  51. End If
  52. For i = 0 To UBound(items)
  53. pos = name & "[" & i & "]"
  54. Set o = JsonLite_Parse(items(i))
  55. If o Is Nothing Then
  56. Load = pos & " must be an object."
  57. Exit Function
  58. End If
  59. kind = LCase("" & StrField(o, "kind"))
  60. id = "" & StrField(o, "id")
  61. role = LCase("" & StrField(o, "role"))
  62. excerpt = StrField(o, "excerpt")
  63. If Len(role) = 0 Then
  64. role = "supports"
  65. End If
  66. If kind <> "experience" And kind <> "chunk" And kind <> "memory" And kind <> "document" Then
  67. Load = pos & ".kind must be experience, chunk, memory or document."
  68. Exit Function
  69. End If
  70. If role <> "supports" And role <> "contradicts" And role <> "context" Then
  71. Load = pos & ".role must be supports, contradicts or context."
  72. Exit Function
  73. End If
  74. If Not IsNull(excerpt) Then
  75. If Len(excerpt) > 2000 Then
  76. Load = pos & ".excerpt must be at most 2000 characters."
  77. Exit Function
  78. End If
  79. End If
  80. If Not Api_IsId(id) Then
  81. Load = pos & ".id must be a valid id."
  82. Exit Function
  83. End If
  84. ' Resolve the target in this tenant; a target the caller cannot read is reported like a missing one.
  85. ns = ""
  86. rev = Null
  87. Select Case kind
  88. Case "experience"
  89. Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  90. If Not rs.EOF Then
  91. ns = "" & rs(0)
  92. End If
  93. rs.Close
  94. Case "chunk"
  95. Set rs = DAL().Query("SELECT d.namespace_id, c.document_revision FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId))
  96. If Not rs.EOF Then
  97. ns = "" & rs(0)
  98. rev = CLng(rs(1))
  99. End If
  100. rs.Close
  101. Case "memory"
  102. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  103. If Not rs.EOF Then
  104. ns = "" & rs(0)
  105. rev = CLng(rs(1))
  106. End If
  107. rs.Close
  108. Case "document"
  109. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM documents WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  110. If Not rs.EOF Then
  111. ns = "" & rs(0)
  112. rev = CLng(rs(1))
  113. End If
  114. rs.Close
  115. End Select
  116. If Len(ns) = 0 Then
  117. Load = pos & " was not found."
  118. Exit Function
  119. End If
  120. If Not Api_CanAccessNamespace(ns, "read") Then
  121. Load = pos & " was not found."
  122. Exit Function
  123. End If
  124. m_kind(m_n) = kind
  125. m_id(m_n) = id
  126. m_rev(m_n) = rev
  127. m_role(m_n) = role
  128. m_excerpt(m_n) = excerpt
  129. m_n = m_n + 1
  130. Next
  131. End Function
  132. Private Function StrField(o, k)
  133. Dim v
  134. StrField = Null
  135. If o.Exists(k) Then
  136. v = o.Item(k)
  137. If VarType(v) = vbString Then
  138. StrField = v
  139. End If
  140. End If
  141. End Function
  142. ' Writes the links (call inside the caller's transaction). ownerRevision: memory revision, or Null for candidates.
  143. Public Sub Save(ownerKind, ownerId, ownerRevision)
  144. Dim i, linkId
  145. For i = 0 To m_n - 1
  146. linkId = Api_NewId()
  147. DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  148. Array(linkId, Api_TenantId, ownerKind, ownerId, m_kind(i), m_id(i), Api_PrincipalId, Api_Now())
  149. DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
  150. Array(ownerRevision, m_rev(i), m_role(i), m_excerpt(i), linkId)
  151. Next
  152. End Sub
  153. End Class
  154. ' Copies a candidate's evidence to a memory revision (candidate acceptance; inside the transaction)
  155. Sub Evidence_CopyCandidate(candidateId, memoryId, revision)
  156. Dim rs, rows, i, linkId
  157. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt FROM evidence_links WHERE owner_kind = 'candidate' AND owner_id = ?", candidateId)
  158. rows = Empty
  159. If Not rs.EOF Then
  160. rows = rs.GetRows()
  161. End If
  162. rs.Close
  163. If IsEmpty(rows) Then
  164. Exit Sub
  165. End If
  166. For i = 0 To UBound(rows, 2)
  167. linkId = Api_NewId()
  168. DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, 'memory', ?, ?, ?, ?, ?)", _
  169. Array(linkId, Api_TenantId, memoryId, "" & rows(0, i), "" & rows(1, i), Api_PrincipalId, Api_Now())
  170. DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
  171. Array(CLng(revision), rows(2, i), "" & rows(3, i), rows(4, i), linkId)
  172. Next
  173. End Sub
  174. ' Evidence of an owner as a JSON array. A target the caller cannot read (or that is gone) is shown without its id.
  175. Function Evidence_Json(ownerKind, ownerId, ownerRev)
  176. Dim rs, rows, i, out, kind, tid, ns, avail, r2
  177. If IsNull(ownerRev) Then
  178. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND tenant_id = ? ORDER BY created_at, id", _
  179. Array(ownerKind, ownerId, Api_TenantId))
  180. Else
  181. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND owner_revision = ? AND tenant_id = ? ORDER BY created_at, id", _
  182. Array(ownerKind, ownerId, CLng(ownerRev), Api_TenantId))
  183. End If
  184. rows = Empty
  185. If Not rs.EOF Then
  186. rows = rs.GetRows()
  187. End If
  188. rs.Close
  189. out = ""
  190. If Not IsEmpty(rows) Then
  191. For i = 0 To UBound(rows, 2)
  192. kind = "" & rows(0, i)
  193. tid = "" & rows(1, i)
  194. ns = Evidence_TargetNamespace(kind, tid)
  195. avail = False
  196. If Len(ns) > 0 Then
  197. avail = Api_CanAccessNamespace(ns, "read")
  198. End If
  199. If i > 0 Then
  200. out = out & ","
  201. End If
  202. out = out & "{""kind"":" & JsonLite_Quote(kind)
  203. If avail Then
  204. out = out & ",""id"":" & JsonLite_Quote(tid) & ",""revision"":" & Evidence_JNum(rows(2, i))
  205. End If
  206. out = out & ",""available"":" & LCase(CStr(avail)) & ",""role"":" & JsonLite_Quote("" & rows(3, i))
  207. If avail Then
  208. out = out & ",""excerpt"":" & Evidence_JStr(rows(4, i))
  209. End If
  210. out = out & ",""content_trust"":"""
  211. If kind = "chunk" Or kind = "document" Then
  212. out = out & "untrusted_reference"
  213. Else
  214. out = out & "evidence"
  215. End If
  216. out = out & """}"
  217. Next
  218. End If
  219. Evidence_Json = "[" & out & "]"
  220. End Function
  221. Function Evidence_TargetNamespace(kind, tid)
  222. Dim rs
  223. Evidence_TargetNamespace = ""
  224. Select Case kind
  225. Case "experience"
  226. Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  227. Case "chunk"
  228. Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(tid, Api_TenantId))
  229. Case "memory"
  230. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  231. Case Else
  232. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  233. End Select
  234. If Not rs.EOF Then
  235. Evidence_TargetNamespace = "" & rs(0)
  236. End If
  237. rs.Close
  238. End Function
  239. Function Evidence_JStr(v)
  240. If IsNull(v) Then
  241. Evidence_JStr = "null"
  242. Else
  243. Evidence_JStr = JsonLite_Quote("" & v)
  244. End If
  245. End Function
  246. Function Evidence_JNum(v)
  247. If IsNull(v) Then
  248. Evidence_JNum = "null"
  249. ElseIf Len("" & v) = 0 Then
  250. Evidence_JNum = "null"
  251. Else
  252. Evidence_JNum = JsonLite_Num(v)
  253. End If
  254. End Function
  255. '-----------------------------------------------------------------------------------------------------------------------
  256. ' Memory writes (inside a transaction)
  257. '-----------------------------------------------------------------------------------------------------------------------
  258. ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps.
  259. Sub Mem_InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
  260. DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
  261. "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
  262. DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
  263. Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
  264. End Sub
  265. Function Mem_Hash(nsId, memType, title, content)
  266. Mem_Hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
  267. End Function
  268. ' New memory, revision 1. Returns the id.
  269. Function Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, reason)
  270. Dim memId, ts
  271. memId = Api_NewId()
  272. ts = Api_Now()
  273. DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _
  274. "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts)
  275. Mem_InsertRevision Api_NewId(), memId, 1, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts
  276. Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw
  277. Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1
  278. Mem_Create = memId
  279. End Function
  280. ' New revision curRev + 1 of an existing memory (type and namespace unchanged). Returns the new revision number.
  281. Function Mem_Revise(memId, nsId, memType, curRev, title, summary, content, tagsRaw, confidence, reason)
  282. Dim newRev, ts
  283. newRev = curRev + 1
  284. ts = Api_Now()
  285. Mem_InsertRevision Api_NewId(), memId, newRev, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts
  286. Search_IndexMemory memId, newRev, Api_TenantId, nsId, title, content, tagsRaw
  287. Emb_MarkPending "memory", memId, Api_TenantId, nsId, newRev
  288. DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _
  289. Array(newRev, ts, memId, Api_TenantId, CLng(curRev))
  290. Mem_Revise = newRev
  291. End Function
  292. Sub Mem_Verify(memId, revision, method, notes)
  293. DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, 'verified', ?, ?, ?)", _
  294. Array(Api_NewId(), memId, CLng(revision), method, notes, Api_PrincipalId, Api_Now())
  295. DAL().Execute "UPDATE memory_revisions SET verification_status = 'verified' WHERE memory_id = ? AND revision = ?", Array(memId, CLng(revision))
  296. End Sub
  297. ' Derived and linked data of a memory that is being forgotten (inside the forget transaction, AC-13)
  298. Sub Mem_ForgetLinked(memId)
  299. DAL().Execute "DELETE FROM evidence_links WHERE owner_kind = 'memory' AND owner_id = ?", memId
  300. ' Edges need valid endpoints (spec 8.1): drop every relationship touching the memory
  301. Graph_ForgetNode "memory", memId
  302. DAL().Execute "DELETE FROM verifications WHERE memory_id = ?", memId
  303. DAL().Execute "DELETE FROM feedback WHERE target_kind = 'memory' AND target_id = ?", memId
  304. DAL().Execute "DELETE FROM retrieval_results WHERE target_kind = 'memory' AND target_id = ?", memId
  305. ' Open proposals to revise it can no longer be applied; all candidates drop the reference (foreign key)
  306. DAL().Execute "UPDATE learning_candidates SET state = 'rejected', review_notes = 'target memory was forgotten', reviewed_at = ? " & _
  307. "WHERE target_memory_id = ? AND state = 'proposed'", Array(Api_Now(), memId)
  308. DAL().Execute "UPDATE learning_candidates SET target_memory_id = NULL WHERE target_memory_id = ?", memId
  309. End Sub
  310. '-----------------------------------------------------------------------------------------------------------------------
  311. ' Retrieval telemetry (never fails the retrieval)
  312. '-----------------------------------------------------------------------------------------------------------------------
  313. Function Tel_NewQueryId()
  314. Tel_NewQueryId = "qry-" & Api_NewId()
  315. End Function
  316. Sub Tel_AddResult(ByRef spec, kind, id, revision, score)
  317. If Len(spec) > 0 Then
  318. spec = spec & Chr(30)
  319. End If
  320. spec = spec & kind & "|" & id & "|" & CLng(revision) & "|" & JsonLite_Num(score)
  321. End Sub
  322. Sub Tel_Record(queryId, operation, strategy, queryText, spec, startTimer)
  323. Dim items, i, parts, ms, cnt
  324. On Error Resume Next
  325. If Len(spec) = 0 Then
  326. items = Array()
  327. Else
  328. items = Split(spec, Chr(30))
  329. End If
  330. cnt = UBound(items) + 1
  331. ms = CLng((Timer - startTimer) * 1000)
  332. If ms < 0 Then
  333. ms = 0
  334. End If
  335. DAL().BeginTransaction
  336. DAL().Execute "INSERT INTO retrieval_queries (id, tenant_id, principal_id, operation, strategy, query_hash, result_count, duration_ms, created_at) " & _
  337. "VALUES (?, ?, ?, ?, ?, ?, " & cnt & ", " & ms & ", ?)", Array(queryId, Api_TenantId, Api_PrincipalId, operation, strategy, Api_Sha256("" & queryText), Api_Now())
  338. For i = 0 To cnt - 1
  339. parts = Split(items(i), "|")
  340. DAL().Execute "INSERT OR IGNORE INTO retrieval_results (query_id, target_kind, target_id, target_revision, rank, score) VALUES (?, ?, ?, ?, ?, ?)", _
  341. Array(queryId, parts(0), parts(1), CLng(parts(2)), i + 1, CDbl(Replace(parts(3), ".", Mid(CStr(1.5), 2, 1))))
  342. Next
  343. If Err.Number <> 0 Then
  344. Err.Clear
  345. DAL().RollbackTransaction
  346. Else
  347. DAL().CommitTransaction
  348. End If
  349. Err.Clear
  350. On Error GoTo 0
  351. End Sub
  352. %>

Powered by TurnKey Linux.