Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

285 řádky
14KB

  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. ' Telemetry : Tel_Record queryId, operation, strategy, queryText, resultsSpec, startTimer
  13. ' resultsSpec = "kind|id|revision|score" items joined by Chr(30). Only a hash of the query is kept.
  14. '=======================================================================================================================
  15. Const EVIDENCE_MAX = 20
  16. Class Evidence_Class
  17. Private m_kind(), m_id(), m_rev(), m_role(), m_excerpt(), m_n
  18. Private Sub Class_Initialize()
  19. m_n = 0
  20. ReDim m_kind(EVIDENCE_MAX)
  21. ReDim m_id(EVIDENCE_MAX)
  22. ReDim m_rev(EVIDENCE_MAX)
  23. ReDim m_role(EVIDENCE_MAX)
  24. ReDim m_excerpt(EVIDENCE_MAX)
  25. End Sub
  26. Public Property Get Count()
  27. Count = m_n
  28. End Property
  29. ' Reads and validates input(name): an optional array of {"kind","id","role","excerpt"}.
  30. Public Function Load(input, name)
  31. Dim items, i, o, kind, id, role, excerpt, rev, ns, rs, pos
  32. Load = ""
  33. m_n = 0
  34. If Not input.HasRaw(name) Then
  35. If input.Exists(name) Then
  36. If Not IsNull(input.Item(name)) Then
  37. Load = name & " must be an array of objects."
  38. End If
  39. End If
  40. Exit Function
  41. End If
  42. items = JsonLite_SplitObjectArray(input.Raw(name))
  43. If IsNull(items) Then
  44. Load = name & " must be an array of objects."
  45. Exit Function
  46. End If
  47. If UBound(items) + 1 > EVIDENCE_MAX Then
  48. Load = name & " may contain at most " & EVIDENCE_MAX & " items."
  49. Exit Function
  50. End If
  51. For i = 0 To UBound(items)
  52. pos = name & "[" & i & "]"
  53. Set o = JsonLite_Parse(items(i))
  54. If o Is Nothing Then
  55. Load = pos & " must be an object."
  56. Exit Function
  57. End If
  58. kind = LCase("" & StrField(o, "kind"))
  59. id = "" & StrField(o, "id")
  60. role = LCase("" & StrField(o, "role"))
  61. excerpt = StrField(o, "excerpt")
  62. If Len(role) = 0 Then
  63. role = "supports"
  64. End If
  65. If kind <> "experience" And kind <> "chunk" And kind <> "memory" And kind <> "document" Then
  66. Load = pos & ".kind must be experience, chunk, memory or document."
  67. Exit Function
  68. End If
  69. If role <> "supports" And role <> "contradicts" And role <> "context" Then
  70. Load = pos & ".role must be supports, contradicts or context."
  71. Exit Function
  72. End If
  73. If Not IsNull(excerpt) Then
  74. If Len(excerpt) > 2000 Then
  75. Load = pos & ".excerpt must be at most 2000 characters."
  76. Exit Function
  77. End If
  78. End If
  79. If Not Api_IsId(id) Then
  80. Load = pos & ".id must be a valid id."
  81. Exit Function
  82. End If
  83. ' Resolve the target in this tenant; a target the caller cannot read is reported like a missing one.
  84. ns = ""
  85. rev = Null
  86. Select Case kind
  87. Case "experience"
  88. Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  89. If Not rs.EOF Then
  90. ns = "" & rs(0)
  91. End If
  92. rs.Close
  93. Case "chunk"
  94. 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))
  95. If Not rs.EOF Then
  96. ns = "" & rs(0)
  97. rev = CLng(rs(1))
  98. End If
  99. rs.Close
  100. Case "memory"
  101. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  102. If Not rs.EOF Then
  103. ns = "" & rs(0)
  104. rev = CLng(rs(1))
  105. End If
  106. rs.Close
  107. Case "document"
  108. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM documents WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  109. If Not rs.EOF Then
  110. ns = "" & rs(0)
  111. rev = CLng(rs(1))
  112. End If
  113. rs.Close
  114. End Select
  115. If Len(ns) = 0 Then
  116. Load = pos & " was not found."
  117. Exit Function
  118. End If
  119. If Not Api_CanAccessNamespace(ns, "read") Then
  120. Load = pos & " was not found."
  121. Exit Function
  122. End If
  123. m_kind(m_n) = kind
  124. m_id(m_n) = id
  125. m_rev(m_n) = rev
  126. m_role(m_n) = role
  127. m_excerpt(m_n) = excerpt
  128. m_n = m_n + 1
  129. Next
  130. End Function
  131. Private Function StrField(o, k)
  132. Dim v
  133. StrField = Null
  134. If o.Exists(k) Then
  135. v = o.Item(k)
  136. If VarType(v) = vbString Then
  137. StrField = v
  138. End If
  139. End If
  140. End Function
  141. ' Writes the links (call inside the caller's transaction). ownerRevision: memory revision, or Null for candidates.
  142. Public Sub Save(ownerKind, ownerId, ownerRevision)
  143. Dim i, linkId
  144. For i = 0 To m_n - 1
  145. linkId = Api_NewId()
  146. DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  147. Array(linkId, Api_TenantId, ownerKind, ownerId, m_kind(i), m_id(i), Api_PrincipalId, Api_Now())
  148. DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
  149. Array(ownerRevision, m_rev(i), m_role(i), m_excerpt(i), linkId)
  150. Next
  151. End Sub
  152. End Class
  153. ' Copies a candidate's evidence to a memory revision (candidate acceptance; inside the transaction)
  154. Sub Evidence_CopyCandidate(candidateId, memoryId, revision)
  155. Dim rs, rows, i, linkId
  156. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt FROM evidence_links WHERE owner_kind = 'candidate' AND owner_id = ?", candidateId)
  157. rows = Empty
  158. If Not rs.EOF Then
  159. rows = rs.GetRows()
  160. End If
  161. rs.Close
  162. If IsEmpty(rows) Then
  163. Exit Sub
  164. End If
  165. For i = 0 To UBound(rows, 2)
  166. linkId = Api_NewId()
  167. DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, 'memory', ?, ?, ?, ?, ?)", _
  168. Array(linkId, Api_TenantId, memoryId, "" & rows(0, i), "" & rows(1, i), Api_PrincipalId, Api_Now())
  169. DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
  170. Array(CLng(revision), rows(2, i), "" & rows(3, i), rows(4, i), linkId)
  171. Next
  172. End Sub
  173. '-----------------------------------------------------------------------------------------------------------------------
  174. ' Memory writes (inside a transaction)
  175. '-----------------------------------------------------------------------------------------------------------------------
  176. ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps.
  177. Sub Mem_InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
  178. DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
  179. "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
  180. DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
  181. Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
  182. End Sub
  183. Function Mem_Hash(nsId, memType, title, content)
  184. Mem_Hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
  185. End Function
  186. ' New memory, revision 1. Returns the id.
  187. Function Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, reason)
  188. Dim memId, ts
  189. memId = Api_NewId()
  190. ts = Api_Now()
  191. DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _
  192. "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts)
  193. Mem_InsertRevision Api_NewId(), memId, 1, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts
  194. Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw
  195. Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1
  196. Mem_Create = memId
  197. End Function
  198. ' New revision curRev + 1 of an existing memory (type and namespace unchanged). Returns the new revision number.
  199. Function Mem_Revise(memId, nsId, memType, curRev, title, summary, content, tagsRaw, confidence, reason)
  200. Dim newRev, ts
  201. newRev = curRev + 1
  202. ts = Api_Now()
  203. Mem_InsertRevision Api_NewId(), memId, newRev, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts
  204. Search_IndexMemory memId, newRev, Api_TenantId, nsId, title, content, tagsRaw
  205. Emb_MarkPending "memory", memId, Api_TenantId, nsId, newRev
  206. DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _
  207. Array(newRev, ts, memId, Api_TenantId, CLng(curRev))
  208. Mem_Revise = newRev
  209. End Function
  210. Sub Mem_Verify(memId, revision, method, notes)
  211. DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, 'verified', ?, ?, ?)", _
  212. Array(Api_NewId(), memId, CLng(revision), method, notes, Api_PrincipalId, Api_Now())
  213. DAL().Execute "UPDATE memory_revisions SET verification_status = 'verified' WHERE memory_id = ? AND revision = ?", Array(memId, CLng(revision))
  214. End Sub
  215. ' Derived and linked data of a memory that is being forgotten (inside the forget transaction, AC-13)
  216. Sub Mem_ForgetLinked(memId)
  217. DAL().Execute "DELETE FROM evidence_links WHERE owner_kind = 'memory' AND owner_id = ?", memId
  218. DAL().Execute "DELETE FROM verifications WHERE memory_id = ?", memId
  219. DAL().Execute "DELETE FROM feedback WHERE target_kind = 'memory' AND target_id = ?", memId
  220. DAL().Execute "DELETE FROM retrieval_results WHERE target_kind = 'memory' AND target_id = ?", memId
  221. ' Open proposals to revise it can no longer be applied; all candidates drop the reference (foreign key)
  222. DAL().Execute "UPDATE learning_candidates SET state = 'rejected', review_notes = 'target memory was forgotten', reviewed_at = ? " & _
  223. "WHERE target_memory_id = ? AND state = 'proposed'", Array(Api_Now(), memId)
  224. DAL().Execute "UPDATE learning_candidates SET target_memory_id = NULL WHERE target_memory_id = ?", memId
  225. End Sub
  226. '-----------------------------------------------------------------------------------------------------------------------
  227. ' Retrieval telemetry (never fails the retrieval)
  228. '-----------------------------------------------------------------------------------------------------------------------
  229. Function Tel_NewQueryId()
  230. Tel_NewQueryId = "qry-" & Api_NewId()
  231. End Function
  232. Sub Tel_AddResult(ByRef spec, kind, id, revision, score)
  233. If Len(spec) > 0 Then
  234. spec = spec & Chr(30)
  235. End If
  236. spec = spec & kind & "|" & id & "|" & CLng(revision) & "|" & JsonLite_Num(score)
  237. End Sub
  238. Sub Tel_Record(queryId, operation, strategy, queryText, spec, startTimer)
  239. Dim items, i, parts, ms, cnt
  240. On Error Resume Next
  241. If Len(spec) = 0 Then
  242. items = Array()
  243. Else
  244. items = Split(spec, Chr(30))
  245. End If
  246. cnt = UBound(items) + 1
  247. ms = CLng((Timer - startTimer) * 1000)
  248. If ms < 0 Then
  249. ms = 0
  250. End If
  251. DAL().BeginTransaction
  252. DAL().Execute "INSERT INTO retrieval_queries (id, tenant_id, principal_id, operation, strategy, query_hash, result_count, duration_ms, created_at) " & _
  253. "VALUES (?, ?, ?, ?, ?, ?, " & cnt & ", " & ms & ", ?)", Array(queryId, Api_TenantId, Api_PrincipalId, operation, strategy, Api_Sha256("" & queryText), Api_Now())
  254. For i = 0 To cnt - 1
  255. parts = Split(items(i), "|")
  256. DAL().Execute "INSERT OR IGNORE INTO retrieval_results (query_id, target_kind, target_id, target_revision, rank, score) VALUES (?, ?, ?, ?, ?, ?)", _
  257. Array(queryId, parts(0), parts(1), CLng(parts(2)), i + 1, CDbl(Replace(parts(3), ".", Mid(CStr(1.5), 2, 1))))
  258. Next
  259. If Err.Number <> 0 Then
  260. Err.Clear
  261. DAL().RollbackTransaction
  262. Else
  263. DAL().CommitTransaction
  264. End If
  265. Err.Clear
  266. On Error GoTo 0
  267. End Sub
  268. %>

Powered by TurnKey Linux.