claude-smart 0.2.47 → 0.2.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/dashboard/app/sessions/[sessionId]/page.tsx +36 -2
- package/plugin/dashboard/package-lock.json +61 -390
- package/plugin/dashboard/package.json +2 -2
- package/plugin/pyproject.toml +1 -1
- package/plugin/uv.lock +1 -1
- package/plugin/vendor/reflexio/.env.example +7 -0
- package/plugin/vendor/reflexio/pyproject.toml +2 -1
- package/plugin/vendor/reflexio/reflexio/README.md +8 -5
- package/plugin/vendor/reflexio/reflexio/lib/_config.py +23 -18
- package/plugin/vendor/reflexio/reflexio/lib/_interactions.py +16 -1
- package/plugin/vendor/reflexio/reflexio/lib/_search.py +15 -11
- package/plugin/vendor/reflexio/reflexio/models/api_schema/domain/enums.py +1 -0
- package/plugin/vendor/reflexio/reflexio/models/config_schema.py +24 -3
- package/plugin/vendor/reflexio/reflexio/server/README.md +25 -8
- package/plugin/vendor/reflexio/reflexio/server/__init__.py +21 -2
- package/plugin/vendor/reflexio/reflexio/server/api.py +133 -3273
- package/plugin/vendor/reflexio/reflexio/server/api_endpoints/README.md +4 -3
- package/plugin/vendor/reflexio/reflexio/server/api_endpoints/publisher_api.py +16 -1
- package/plugin/vendor/reflexio/reflexio/server/cache/reflexio_cache.py +62 -36
- package/plugin/vendor/reflexio/reflexio/server/deployment_profile.py +69 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_embedding.py +424 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_json_extraction.py +249 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_structured_output.py +195 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_subprocess.py +152 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_text_generation.py +980 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_types.py +110 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/litellm_client.py +73 -1819
- package/plugin/vendor/reflexio/reflexio/server/llm/providers/claude_code_provider.py +56 -4
- package/plugin/vendor/reflexio/reflexio/server/middleware.py +244 -0
- package/plugin/vendor/reflexio/reflexio/server/operation_limiter.py +9 -1
- package/plugin/vendor/reflexio/reflexio/server/rate_limit.py +79 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/__init__.py +6 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/_common.py +25 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/_metering.py +98 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/braintrust.py +129 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/config.py +210 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/evaluation.py +549 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/interactions.py +259 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/playbooks.py +578 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/profiles.py +423 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/provenance.py +345 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/search.py +349 -0
- package/plugin/vendor/reflexio/reflexio/server/routes/system.py +261 -0
- package/plugin/vendor/reflexio/reflexio/server/scheduling.py +132 -0
- package/plugin/vendor/reflexio/reflexio/server/services/README.md +3 -2
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/__init__.py +38 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_batch_progress.py +298 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_config_filter.py +152 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_extraction_lifecycle.py +243 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_should_run.py +299 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_status_change.py +273 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_usage_billing.py +258 -0
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation_service.py +17 -1183
- package/plugin/vendor/reflexio/reflexio/server/services/deduplication_utils.py +8 -1
- package/plugin/vendor/reflexio/reflexio/server/services/extraction/resume_scheduler.py +26 -41
- package/plugin/vendor/reflexio/reflexio/server/services/generation_service.py +232 -123
- package/plugin/vendor/reflexio/reflexio/server/services/lineage/gc_scheduler.py +362 -81
- package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator.py +68 -490
- package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator_clustering.py +184 -0
- package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator_postprocessing.py +130 -0
- package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator_prompt_formatting.py +212 -0
- package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/consolidator.py +258 -69
- package/plugin/vendor/reflexio/reflexio/server/services/publish_learning_worker.py +288 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/__init__.py +29 -4
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_agent_run.py +10 -1167
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_base.py +56 -351
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_governance.py +0 -1513
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_lineage.py +6 -1
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_profiles.py +7 -1281
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_share_links.py +30 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/__init__.py +9 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/_agent_run_store.py +506 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/_pending_tool_call_store.py +704 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/_run_tool_dependency_store.py +123 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/base/__init__.py +6 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/base/_deletion.py +263 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/base/_fts_vec.py +132 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/__init__.py +13 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_audit.py +122 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_erase_execution.py +465 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_purge.py +387 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_rebuild_hide.py +332 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_subject_barrier.py +511 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_agent.py +6 -3
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_user.py +13 -7
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/__init__.py +9 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/_interaction_store.py +263 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/_profile_store.py +896 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/_search.py +270 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/__init__.py +33 -8
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_agent_run.py +64 -370
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_share_links.py +20 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/__init__.py +9 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_agent_run_store.py +86 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_models.py +195 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_pending_tool_call_store.py +148 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_run_tool_dependency_store.py +38 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/__init__.py +13 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_audit.py +29 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_erase_execution.py +30 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_purge.py +74 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_rebuild_hide.py +32 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_subject_barrier.py +49 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/profiles/__init__.py +9 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/profiles/_interaction_store.py +73 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/{_profiles.py → profiles/_profile_store.py} +44 -86
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/profiles/_search.py +32 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_governance.py +0 -148
|
@@ -0,0 +1,896 @@
|
|
|
1
|
+
"""Profile store CRUD methods for SQLite storage.
|
|
2
|
+
|
|
3
|
+
Extracted verbatim from ``_profiles.py`` (the ProfileStore bucket). Interaction
|
|
4
|
+
methods live in ``profiles._interaction_store`` (``InteractionStoreMixin``);
|
|
5
|
+
search methods live in ``profiles._search`` (``ProfileSearchMixin``).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import sqlite3
|
|
10
|
+
import uuid
|
|
11
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from reflexio.models.api_schema.service_schemas import (
|
|
15
|
+
DeleteUserProfileRequest,
|
|
16
|
+
Status,
|
|
17
|
+
UserProfile,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from .._base import (
|
|
21
|
+
_PROFILE_TOMBSTONE_STATUS_VALUES,
|
|
22
|
+
SQLiteStorageBase,
|
|
23
|
+
_build_status_sql,
|
|
24
|
+
_epoch_now,
|
|
25
|
+
_iso_now,
|
|
26
|
+
_json_dumps,
|
|
27
|
+
_row_to_profile,
|
|
28
|
+
)
|
|
29
|
+
from .._lineage import _GC_ELIGIBLE_STATUSES, _append_event_stmt
|
|
30
|
+
from .._profiles import _build_tags_sql
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _emit_hard_delete_profile(
|
|
36
|
+
conn: sqlite3.Connection,
|
|
37
|
+
*,
|
|
38
|
+
org_id: str,
|
|
39
|
+
entity_id: str,
|
|
40
|
+
request_id: str,
|
|
41
|
+
actor: str = "api",
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Emit a single hard_delete lineage event for a profile entity."""
|
|
44
|
+
_append_event_stmt(
|
|
45
|
+
conn,
|
|
46
|
+
org_id=org_id,
|
|
47
|
+
entity_type="profile",
|
|
48
|
+
entity_id=entity_id,
|
|
49
|
+
op="hard_delete",
|
|
50
|
+
prov="wasInvalidatedBy",
|
|
51
|
+
source_ids=[],
|
|
52
|
+
actor=actor,
|
|
53
|
+
request_id=request_id,
|
|
54
|
+
reason="erasure",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _escape_like_pattern(value: str) -> str:
|
|
59
|
+
return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ProfileStoreMixin:
|
|
63
|
+
"""Mixin providing profile-store CRUD for SQLite storage."""
|
|
64
|
+
|
|
65
|
+
# Type hints for instance attributes/methods provided by SQLiteStorageBase via MRO
|
|
66
|
+
_lock: Any
|
|
67
|
+
conn: sqlite3.Connection
|
|
68
|
+
org_id: str
|
|
69
|
+
_fetchone: Any
|
|
70
|
+
_fetchall: Any
|
|
71
|
+
_get_embedding: Any
|
|
72
|
+
_should_expand_documents: Any
|
|
73
|
+
_expand_document: Any
|
|
74
|
+
_fts_upsert_profile: Any
|
|
75
|
+
_vec_upsert: Any
|
|
76
|
+
_delete_in_chunks: Any
|
|
77
|
+
_has_sqlite_vec: bool
|
|
78
|
+
_subject_ref_for_user_id: Any
|
|
79
|
+
_assert_subject_writable_locked: Any
|
|
80
|
+
|
|
81
|
+
def _subject_ref_from_profile_row(self, row: sqlite3.Row) -> str:
|
|
82
|
+
subject_ref = row["governance_subject_ref"]
|
|
83
|
+
return (
|
|
84
|
+
str(subject_ref)
|
|
85
|
+
if subject_ref
|
|
86
|
+
else self._subject_ref_for_user_id(row["user_id"])
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _assert_profile_writable_locked(
|
|
90
|
+
self,
|
|
91
|
+
profile_id: str,
|
|
92
|
+
*,
|
|
93
|
+
user_id: str | None = None,
|
|
94
|
+
) -> sqlite3.Row | None:
|
|
95
|
+
if user_id is None:
|
|
96
|
+
row = self.conn.execute(
|
|
97
|
+
"SELECT user_id, governance_subject_ref FROM profiles WHERE profile_id = ?",
|
|
98
|
+
(profile_id,),
|
|
99
|
+
).fetchone()
|
|
100
|
+
else:
|
|
101
|
+
row = self.conn.execute(
|
|
102
|
+
"SELECT user_id, governance_subject_ref FROM profiles WHERE profile_id = ? AND user_id = ?",
|
|
103
|
+
(profile_id, user_id),
|
|
104
|
+
).fetchone()
|
|
105
|
+
if row is None:
|
|
106
|
+
return None
|
|
107
|
+
self._assert_subject_writable_locked(self._subject_ref_from_profile_row(row))
|
|
108
|
+
return row
|
|
109
|
+
|
|
110
|
+
@SQLiteStorageBase.handle_exceptions
|
|
111
|
+
def get_all_profiles(
|
|
112
|
+
self,
|
|
113
|
+
limit: int = 100,
|
|
114
|
+
status_filter: list[Status | None] | None = None,
|
|
115
|
+
user_id: str | None = None,
|
|
116
|
+
profile_id: str | None = None,
|
|
117
|
+
query: str | None = None,
|
|
118
|
+
source: str | None = None,
|
|
119
|
+
profile_time_to_live: str | None = None,
|
|
120
|
+
start_time: int | None = None,
|
|
121
|
+
end_time: int | None = None,
|
|
122
|
+
) -> list[UserProfile]:
|
|
123
|
+
if status_filter is None:
|
|
124
|
+
status_filter = [None]
|
|
125
|
+
frag, params = _build_status_sql(status_filter)
|
|
126
|
+
conditions = [frag]
|
|
127
|
+
if user_id:
|
|
128
|
+
conditions.append("user_id = ?")
|
|
129
|
+
params.append(user_id)
|
|
130
|
+
if profile_id:
|
|
131
|
+
conditions.append("LOWER(profile_id) = LOWER(?)")
|
|
132
|
+
params.append(profile_id)
|
|
133
|
+
if query:
|
|
134
|
+
like = f"%{_escape_like_pattern(query.lower())}%"
|
|
135
|
+
conditions.append(
|
|
136
|
+
"(LOWER(content) LIKE ? ESCAPE '\\' OR LOWER(profile_id) LIKE ? ESCAPE '\\' OR LOWER(user_id) LIKE ? ESCAPE '\\')"
|
|
137
|
+
)
|
|
138
|
+
params.extend([like, like, like])
|
|
139
|
+
if source is not None:
|
|
140
|
+
conditions.append("source = ?")
|
|
141
|
+
params.append(source)
|
|
142
|
+
if profile_time_to_live:
|
|
143
|
+
conditions.append("profile_time_to_live = ?")
|
|
144
|
+
params.append(profile_time_to_live)
|
|
145
|
+
if start_time is not None:
|
|
146
|
+
conditions.append("last_modified_timestamp >= ?")
|
|
147
|
+
params.append(start_time)
|
|
148
|
+
if end_time is not None:
|
|
149
|
+
conditions.append("last_modified_timestamp <= ?")
|
|
150
|
+
params.append(end_time)
|
|
151
|
+
sql = (
|
|
152
|
+
f"SELECT * FROM profiles WHERE {' AND '.join(conditions)} "
|
|
153
|
+
"ORDER BY last_modified_timestamp DESC LIMIT ?"
|
|
154
|
+
)
|
|
155
|
+
params.append(limit)
|
|
156
|
+
return [_row_to_profile(r) for r in self._fetchall(sql, params)]
|
|
157
|
+
|
|
158
|
+
@SQLiteStorageBase.handle_exceptions
|
|
159
|
+
def get_user_profile(
|
|
160
|
+
self,
|
|
161
|
+
user_id: str,
|
|
162
|
+
status_filter: list[Status | None] | None = None,
|
|
163
|
+
tags: list[str] | None = None,
|
|
164
|
+
profile_id: str | None = None,
|
|
165
|
+
query: str | None = None,
|
|
166
|
+
source: str | None = None,
|
|
167
|
+
profile_time_to_live: str | None = None,
|
|
168
|
+
start_time: int | None = None,
|
|
169
|
+
end_time: int | None = None,
|
|
170
|
+
include_expired: bool = False,
|
|
171
|
+
) -> list[UserProfile]:
|
|
172
|
+
if status_filter is None:
|
|
173
|
+
status_filter = [None]
|
|
174
|
+
frag, params = _build_status_sql(status_filter)
|
|
175
|
+
conditions: list[str] = ["user_id = ?"]
|
|
176
|
+
all_params: list[Any] = [user_id]
|
|
177
|
+
if not include_expired:
|
|
178
|
+
conditions.append("expiration_timestamp >= ?")
|
|
179
|
+
all_params.append(_epoch_now())
|
|
180
|
+
conditions.append(frag)
|
|
181
|
+
all_params.extend(params)
|
|
182
|
+
if profile_id:
|
|
183
|
+
conditions.append("LOWER(profile_id) = LOWER(?)")
|
|
184
|
+
all_params.append(profile_id)
|
|
185
|
+
if query:
|
|
186
|
+
like = f"%{_escape_like_pattern(query.lower())}%"
|
|
187
|
+
conditions.append(
|
|
188
|
+
"(LOWER(content) LIKE ? ESCAPE '\\' OR LOWER(profile_id) LIKE ? ESCAPE '\\' OR LOWER(user_id) LIKE ? ESCAPE '\\')"
|
|
189
|
+
)
|
|
190
|
+
all_params.extend([like, like, like])
|
|
191
|
+
if source is not None:
|
|
192
|
+
conditions.append("source = ?")
|
|
193
|
+
all_params.append(source)
|
|
194
|
+
if profile_time_to_live:
|
|
195
|
+
conditions.append("profile_time_to_live = ?")
|
|
196
|
+
all_params.append(profile_time_to_live)
|
|
197
|
+
if start_time is not None:
|
|
198
|
+
conditions.append("last_modified_timestamp >= ?")
|
|
199
|
+
all_params.append(start_time)
|
|
200
|
+
if end_time is not None:
|
|
201
|
+
conditions.append("last_modified_timestamp <= ?")
|
|
202
|
+
all_params.append(end_time)
|
|
203
|
+
tag_frag, tag_params = _build_tags_sql("profiles", tags)
|
|
204
|
+
if tag_frag:
|
|
205
|
+
conditions.append(tag_frag)
|
|
206
|
+
all_params.extend(tag_params)
|
|
207
|
+
sql = f"SELECT * FROM profiles WHERE {' AND '.join(conditions)}"
|
|
208
|
+
return [_row_to_profile(r) for r in self._fetchall(sql, all_params)]
|
|
209
|
+
|
|
210
|
+
@SQLiteStorageBase.handle_exceptions
|
|
211
|
+
def add_user_profile(self, user_id: str, user_profiles: list[UserProfile]) -> None: # noqa: ARG002
|
|
212
|
+
for profile in user_profiles:
|
|
213
|
+
subject_ref = self._subject_ref_for_user_id(profile.user_id)
|
|
214
|
+
with self._lock:
|
|
215
|
+
self._assert_subject_writable_locked(subject_ref)
|
|
216
|
+
embedding_text = "\n".join([profile.content, str(profile.custom_features)])
|
|
217
|
+
if self._should_expand_documents():
|
|
218
|
+
with ThreadPoolExecutor(max_workers=2) as executor:
|
|
219
|
+
emb_future = executor.submit(self._get_embedding, embedding_text)
|
|
220
|
+
exp_future = executor.submit(self._expand_document, profile.content)
|
|
221
|
+
profile.embedding = emb_future.result(timeout=15)
|
|
222
|
+
profile.expanded_terms = exp_future.result(timeout=15)
|
|
223
|
+
else:
|
|
224
|
+
profile.embedding = self._get_embedding(embedding_text)
|
|
225
|
+
embedding = profile.embedding
|
|
226
|
+
with self._lock:
|
|
227
|
+
try:
|
|
228
|
+
self.conn.execute("BEGIN IMMEDIATE")
|
|
229
|
+
self._assert_subject_writable_locked(subject_ref)
|
|
230
|
+
self.conn.execute(
|
|
231
|
+
"""INSERT OR REPLACE INTO profiles
|
|
232
|
+
(profile_id, user_id, content, last_modified_timestamp,
|
|
233
|
+
generated_from_request_id, profile_time_to_live,
|
|
234
|
+
expiration_timestamp, custom_features, embedding, source,
|
|
235
|
+
status, extractor_names, expanded_terms,
|
|
236
|
+
source_span, notes, reader_angle, tags, source_interaction_ids, created_at,
|
|
237
|
+
merged_into, superseded_by, governance_subject_ref)
|
|
238
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
|
239
|
+
(
|
|
240
|
+
profile.profile_id,
|
|
241
|
+
profile.user_id,
|
|
242
|
+
profile.content,
|
|
243
|
+
profile.last_modified_timestamp,
|
|
244
|
+
profile.generated_from_request_id,
|
|
245
|
+
profile.profile_time_to_live.value,
|
|
246
|
+
profile.expiration_timestamp,
|
|
247
|
+
_json_dumps(profile.custom_features),
|
|
248
|
+
_json_dumps(profile.embedding),
|
|
249
|
+
profile.source,
|
|
250
|
+
profile.status.value if profile.status else None,
|
|
251
|
+
_json_dumps(profile.extractor_names),
|
|
252
|
+
profile.expanded_terms,
|
|
253
|
+
profile.source_span,
|
|
254
|
+
profile.notes,
|
|
255
|
+
profile.reader_angle,
|
|
256
|
+
_json_dumps(profile.tags),
|
|
257
|
+
_json_dumps(profile.source_interaction_ids),
|
|
258
|
+
_iso_now(),
|
|
259
|
+
profile.merged_into,
|
|
260
|
+
profile.superseded_by,
|
|
261
|
+
subject_ref,
|
|
262
|
+
),
|
|
263
|
+
)
|
|
264
|
+
self.conn.commit()
|
|
265
|
+
except Exception:
|
|
266
|
+
self.conn.rollback()
|
|
267
|
+
raise
|
|
268
|
+
fts_parts = [profile.content or ""]
|
|
269
|
+
if profile.custom_features:
|
|
270
|
+
fts_parts.extend(str(v) for v in profile.custom_features.values() if v)
|
|
271
|
+
if profile.expanded_terms:
|
|
272
|
+
fts_parts.append(profile.expanded_terms)
|
|
273
|
+
self._fts_upsert_profile(profile.profile_id, " ".join(fts_parts))
|
|
274
|
+
# Sync vec table — look up implicit rowid via primary key
|
|
275
|
+
row = self._fetchone(
|
|
276
|
+
"SELECT rowid FROM profiles WHERE profile_id = ?",
|
|
277
|
+
(profile.profile_id,),
|
|
278
|
+
)
|
|
279
|
+
if row and embedding:
|
|
280
|
+
self._vec_upsert("profiles_vec", row["rowid"], embedding)
|
|
281
|
+
|
|
282
|
+
@SQLiteStorageBase.handle_exceptions
|
|
283
|
+
def update_user_profile_by_id(
|
|
284
|
+
self, user_id: str, profile_id: str, new_profile: UserProfile
|
|
285
|
+
) -> None:
|
|
286
|
+
"""Replace a profile's content in-place and emit a revise lineage event.
|
|
287
|
+
|
|
288
|
+
Each call generates a fresh request_id so every edit is a distinct audit
|
|
289
|
+
event (not collapsed by the idempotency key). The UPDATE, lineage event,
|
|
290
|
+
FTS sync, and vec sync are all executed inside a single lock acquisition;
|
|
291
|
+
self._lock is an RLock so the inner _fts_upsert_profile/_vec_upsert calls
|
|
292
|
+
that re-acquire it are safe.
|
|
293
|
+
"""
|
|
294
|
+
current_ts = _epoch_now()
|
|
295
|
+
with self._lock:
|
|
296
|
+
row = self.conn.execute(
|
|
297
|
+
"SELECT user_id, governance_subject_ref FROM profiles WHERE user_id = ? AND profile_id = ? AND expiration_timestamp >= ?",
|
|
298
|
+
(user_id, profile_id, current_ts),
|
|
299
|
+
).fetchone()
|
|
300
|
+
if not row:
|
|
301
|
+
logger.warning("User profile not found for user id: %s", user_id)
|
|
302
|
+
return
|
|
303
|
+
self._assert_subject_writable_locked(
|
|
304
|
+
self._subject_ref_from_profile_row(row)
|
|
305
|
+
)
|
|
306
|
+
embedding = self._get_embedding(
|
|
307
|
+
"\n".join([new_profile.content, str(new_profile.custom_features)])
|
|
308
|
+
)
|
|
309
|
+
new_profile.embedding = embedding
|
|
310
|
+
with self._lock:
|
|
311
|
+
if (
|
|
312
|
+
self._assert_profile_writable_locked(profile_id, user_id=user_id)
|
|
313
|
+
is None
|
|
314
|
+
):
|
|
315
|
+
logger.warning("User profile not found for user id: %s", user_id)
|
|
316
|
+
return
|
|
317
|
+
cur = self.conn.execute(
|
|
318
|
+
"""UPDATE profiles SET content=?, last_modified_timestamp=?,
|
|
319
|
+
generated_from_request_id=?, profile_time_to_live=?,
|
|
320
|
+
expiration_timestamp=?, custom_features=?, embedding=?,
|
|
321
|
+
source=?, status=?, extractor_names=?, expanded_terms=?,
|
|
322
|
+
source_span=?, notes=?, reader_angle=?, tags=?, source_interaction_ids=?
|
|
323
|
+
WHERE profile_id=?""",
|
|
324
|
+
(
|
|
325
|
+
new_profile.content,
|
|
326
|
+
new_profile.last_modified_timestamp,
|
|
327
|
+
new_profile.generated_from_request_id,
|
|
328
|
+
new_profile.profile_time_to_live.value,
|
|
329
|
+
new_profile.expiration_timestamp,
|
|
330
|
+
_json_dumps(new_profile.custom_features),
|
|
331
|
+
_json_dumps(new_profile.embedding),
|
|
332
|
+
new_profile.source,
|
|
333
|
+
new_profile.status.value if new_profile.status else None,
|
|
334
|
+
_json_dumps(new_profile.extractor_names),
|
|
335
|
+
new_profile.expanded_terms,
|
|
336
|
+
new_profile.source_span,
|
|
337
|
+
new_profile.notes,
|
|
338
|
+
new_profile.reader_angle,
|
|
339
|
+
_json_dumps(new_profile.tags),
|
|
340
|
+
_json_dumps(new_profile.source_interaction_ids),
|
|
341
|
+
profile_id,
|
|
342
|
+
),
|
|
343
|
+
)
|
|
344
|
+
if cur.rowcount > 0:
|
|
345
|
+
_append_event_stmt(
|
|
346
|
+
self.conn,
|
|
347
|
+
org_id=self.org_id,
|
|
348
|
+
entity_type="profile",
|
|
349
|
+
entity_id=str(profile_id),
|
|
350
|
+
op="revise",
|
|
351
|
+
prov="wasRevisionOf",
|
|
352
|
+
source_ids=[],
|
|
353
|
+
actor="api",
|
|
354
|
+
request_id=uuid.uuid4().hex,
|
|
355
|
+
reason="in-place update",
|
|
356
|
+
)
|
|
357
|
+
self.conn.commit()
|
|
358
|
+
fts_parts = [new_profile.content or ""]
|
|
359
|
+
if new_profile.custom_features:
|
|
360
|
+
fts_parts.extend(
|
|
361
|
+
str(v) for v in new_profile.custom_features.values() if v
|
|
362
|
+
)
|
|
363
|
+
if new_profile.expanded_terms:
|
|
364
|
+
fts_parts.append(new_profile.expanded_terms)
|
|
365
|
+
self._fts_upsert_profile(profile_id, " ".join(fts_parts))
|
|
366
|
+
rowid_row = self._fetchone(
|
|
367
|
+
"SELECT rowid FROM profiles WHERE profile_id = ?", (profile_id,)
|
|
368
|
+
)
|
|
369
|
+
if rowid_row and embedding:
|
|
370
|
+
self._vec_upsert("profiles_vec", rowid_row["rowid"], embedding)
|
|
371
|
+
|
|
372
|
+
@SQLiteStorageBase.handle_exceptions
|
|
373
|
+
def update_user_profile_tags(
|
|
374
|
+
self, user_id: str, profile_id: str, tags: list[str]
|
|
375
|
+
) -> None:
|
|
376
|
+
with self._lock:
|
|
377
|
+
if (
|
|
378
|
+
self._assert_profile_writable_locked(profile_id, user_id=user_id)
|
|
379
|
+
is None
|
|
380
|
+
):
|
|
381
|
+
return
|
|
382
|
+
self.conn.execute(
|
|
383
|
+
"UPDATE profiles SET tags=? WHERE user_id=? AND profile_id=?",
|
|
384
|
+
(_json_dumps(tags), user_id, profile_id),
|
|
385
|
+
)
|
|
386
|
+
self.conn.commit()
|
|
387
|
+
|
|
388
|
+
@SQLiteStorageBase.handle_exceptions
|
|
389
|
+
def delete_user_profile(self, request: DeleteUserProfileRequest) -> None:
|
|
390
|
+
# Atomic: fts + vec + row + lineage in ONE lock/commit to prevent rowid reuse
|
|
391
|
+
# race. profiles uses implicit (reusable) rowid keyed by TEXT PK — a cleanup
|
|
392
|
+
# running after commit could race with a concurrent INSERT reusing the freed
|
|
393
|
+
# rowid and delete the NEW profile's vec row. (#196)
|
|
394
|
+
with self._lock:
|
|
395
|
+
rowid_row = self.conn.execute(
|
|
396
|
+
"SELECT rowid FROM profiles WHERE user_id = ? AND profile_id = ?",
|
|
397
|
+
(request.user_id, request.profile_id),
|
|
398
|
+
).fetchone()
|
|
399
|
+
if rowid_row is None:
|
|
400
|
+
return
|
|
401
|
+
self.conn.execute(
|
|
402
|
+
"DELETE FROM profiles_fts WHERE profile_id = ?",
|
|
403
|
+
(request.profile_id,),
|
|
404
|
+
)
|
|
405
|
+
if self._has_sqlite_vec and rowid_row:
|
|
406
|
+
self.conn.execute(
|
|
407
|
+
"DELETE FROM profiles_vec WHERE rowid = ?",
|
|
408
|
+
(rowid_row["rowid"],),
|
|
409
|
+
)
|
|
410
|
+
cur = self.conn.execute(
|
|
411
|
+
"DELETE FROM profiles WHERE user_id = ? AND profile_id = ?",
|
|
412
|
+
(request.user_id, request.profile_id),
|
|
413
|
+
)
|
|
414
|
+
if cur.rowcount > 0:
|
|
415
|
+
_emit_hard_delete_profile(
|
|
416
|
+
self.conn,
|
|
417
|
+
org_id=self.org_id,
|
|
418
|
+
entity_id=str(request.profile_id),
|
|
419
|
+
request_id=uuid.uuid4().hex,
|
|
420
|
+
)
|
|
421
|
+
self.conn.commit()
|
|
422
|
+
|
|
423
|
+
@SQLiteStorageBase.handle_exceptions
|
|
424
|
+
def delete_all_profiles_for_user(self, user_id: str) -> None:
|
|
425
|
+
# Atomic: fts + vec + row + lineage in ONE lock/commit — rowid reuse race
|
|
426
|
+
# prevention (see delete_user_profile comment, #196).
|
|
427
|
+
batch_request_id = uuid.uuid4().hex
|
|
428
|
+
with self._lock:
|
|
429
|
+
rows = self.conn.execute(
|
|
430
|
+
"SELECT rowid, profile_id FROM profiles WHERE user_id = ?", (user_id,)
|
|
431
|
+
).fetchall()
|
|
432
|
+
if not rows:
|
|
433
|
+
return
|
|
434
|
+
pids = [r["profile_id"] for r in rows]
|
|
435
|
+
rowids = [r["rowid"] for r in rows]
|
|
436
|
+
self._delete_in_chunks("profiles_fts", "profile_id", pids)
|
|
437
|
+
if self._has_sqlite_vec and rowids:
|
|
438
|
+
self._delete_in_chunks("profiles_vec", "rowid", rowids)
|
|
439
|
+
self.conn.execute("DELETE FROM profiles WHERE user_id = ?", (user_id,))
|
|
440
|
+
for pid in pids:
|
|
441
|
+
_emit_hard_delete_profile(
|
|
442
|
+
self.conn,
|
|
443
|
+
org_id=self.org_id,
|
|
444
|
+
entity_id=str(pid),
|
|
445
|
+
request_id=batch_request_id,
|
|
446
|
+
)
|
|
447
|
+
self.conn.commit()
|
|
448
|
+
|
|
449
|
+
@SQLiteStorageBase.handle_exceptions
|
|
450
|
+
def delete_all_profiles(self) -> None:
|
|
451
|
+
# Also wipe profiles_vec (full-wipe variant of the rowid-race fix, #196).
|
|
452
|
+
batch_request_id = uuid.uuid4().hex
|
|
453
|
+
with self._lock:
|
|
454
|
+
pids = [
|
|
455
|
+
r["profile_id"]
|
|
456
|
+
for r in self.conn.execute("SELECT profile_id FROM profiles").fetchall()
|
|
457
|
+
]
|
|
458
|
+
for pid in pids:
|
|
459
|
+
_emit_hard_delete_profile(
|
|
460
|
+
self.conn,
|
|
461
|
+
org_id=self.org_id,
|
|
462
|
+
entity_id=str(pid),
|
|
463
|
+
request_id=batch_request_id,
|
|
464
|
+
)
|
|
465
|
+
self.conn.execute("DELETE FROM profiles_fts")
|
|
466
|
+
if self._has_sqlite_vec:
|
|
467
|
+
self.conn.execute("DELETE FROM profiles_vec")
|
|
468
|
+
self.conn.execute("DELETE FROM profiles")
|
|
469
|
+
self.conn.commit()
|
|
470
|
+
|
|
471
|
+
@SQLiteStorageBase.handle_exceptions
|
|
472
|
+
def count_all_profiles(self) -> int:
|
|
473
|
+
row = self._fetchone("SELECT COUNT(*) as cnt FROM profiles")
|
|
474
|
+
return row["cnt"] if row else 0
|
|
475
|
+
|
|
476
|
+
@SQLiteStorageBase.handle_exceptions
|
|
477
|
+
def update_all_profiles_status(
|
|
478
|
+
self,
|
|
479
|
+
old_status: Status | None,
|
|
480
|
+
new_status: Status | None,
|
|
481
|
+
user_ids: list[str] | None = None,
|
|
482
|
+
) -> int:
|
|
483
|
+
new_val = new_status.value if new_status else None
|
|
484
|
+
now_ts = _epoch_now()
|
|
485
|
+
old_val_str = old_status.value if old_status else "None"
|
|
486
|
+
new_val_str = new_status.value if new_status else "None"
|
|
487
|
+
reason = f"{old_val_str}->{new_val_str}"
|
|
488
|
+
|
|
489
|
+
if old_status is None or (
|
|
490
|
+
hasattr(old_status, "value") and old_status.value is None
|
|
491
|
+
):
|
|
492
|
+
where = "status IS NULL"
|
|
493
|
+
select_params: list[Any] = []
|
|
494
|
+
else:
|
|
495
|
+
where = "status = ?"
|
|
496
|
+
select_params = [old_status.value]
|
|
497
|
+
|
|
498
|
+
extra_params: list[Any] = []
|
|
499
|
+
if user_ids is not None:
|
|
500
|
+
placeholders = ",".join("?" for _ in user_ids)
|
|
501
|
+
where += f" AND user_id IN ({placeholders})"
|
|
502
|
+
extra_params.extend(user_ids)
|
|
503
|
+
|
|
504
|
+
# Set retired_at = now when transitioning to a GC-eligible status; clear to NULL otherwise.
|
|
505
|
+
retired_at_val = now_ts if new_val in _GC_ELIGIBLE_STATUSES else None
|
|
506
|
+
|
|
507
|
+
batch_request_id = uuid.uuid4().hex
|
|
508
|
+
with self._lock:
|
|
509
|
+
affected = list(
|
|
510
|
+
self.conn.execute(
|
|
511
|
+
f"SELECT profile_id, user_id, governance_subject_ref FROM profiles WHERE {where}",
|
|
512
|
+
select_params + extra_params,
|
|
513
|
+
).fetchall()
|
|
514
|
+
)
|
|
515
|
+
for row in affected:
|
|
516
|
+
self._assert_subject_writable_locked(
|
|
517
|
+
self._subject_ref_from_profile_row(row)
|
|
518
|
+
)
|
|
519
|
+
cur = self.conn.execute(
|
|
520
|
+
f"UPDATE profiles SET status = ?, last_modified_timestamp = ?, retired_at = ? WHERE {where}",
|
|
521
|
+
[new_val, now_ts, retired_at_val] + select_params + extra_params,
|
|
522
|
+
)
|
|
523
|
+
from_val = old_status.value if old_status else None
|
|
524
|
+
to_val = new_status.value if new_status else None
|
|
525
|
+
for row in affected:
|
|
526
|
+
pid = row["profile_id"]
|
|
527
|
+
_append_event_stmt(
|
|
528
|
+
self.conn,
|
|
529
|
+
org_id=self.org_id,
|
|
530
|
+
entity_type="profile",
|
|
531
|
+
entity_id=str(pid),
|
|
532
|
+
op="status_change",
|
|
533
|
+
prov="wasInvalidatedBy",
|
|
534
|
+
source_ids=[],
|
|
535
|
+
actor="api",
|
|
536
|
+
request_id=batch_request_id,
|
|
537
|
+
reason=reason,
|
|
538
|
+
from_status=from_val,
|
|
539
|
+
to_status=to_val,
|
|
540
|
+
status_namespace="lifecycle_status",
|
|
541
|
+
)
|
|
542
|
+
self.conn.commit()
|
|
543
|
+
return cur.rowcount
|
|
544
|
+
|
|
545
|
+
@SQLiteStorageBase.handle_exceptions
|
|
546
|
+
def expire_active_profiles(self, *, now: int, limit: int = 1000) -> int:
|
|
547
|
+
"""Tombstone active profiles whose TTL has elapsed.
|
|
548
|
+
|
|
549
|
+
Args:
|
|
550
|
+
now: Current epoch timestamp (seconds). Profiles with
|
|
551
|
+
``expiration_timestamp < now`` are tombstoned.
|
|
552
|
+
limit: Maximum number of profiles to tombstone in one call (default 1000).
|
|
553
|
+
|
|
554
|
+
Returns:
|
|
555
|
+
int: Number of profiles tombstoned.
|
|
556
|
+
"""
|
|
557
|
+
if limit <= 0:
|
|
558
|
+
return 0
|
|
559
|
+
batch_request_id = uuid.uuid4().hex
|
|
560
|
+
with self._lock:
|
|
561
|
+
# BEGIN IMMEDIATE acquires a write lock immediately so no other
|
|
562
|
+
# connection can write between the SELECT and the UPDATE. This
|
|
563
|
+
# ensures the affected-id list == the actually-updated set, making
|
|
564
|
+
# the emitted status_change events correct. Matches the pattern
|
|
565
|
+
# used by expire_pending_tool_calls in sqlite_storage/_agent_run.py.
|
|
566
|
+
self.conn.execute("BEGIN IMMEDIATE")
|
|
567
|
+
try:
|
|
568
|
+
affected = list(
|
|
569
|
+
self.conn.execute(
|
|
570
|
+
"SELECT profile_id, user_id, governance_subject_ref FROM profiles "
|
|
571
|
+
"WHERE status IS NULL AND expiration_timestamp < ? "
|
|
572
|
+
"ORDER BY expiration_timestamp ASC LIMIT ?",
|
|
573
|
+
(now, limit),
|
|
574
|
+
).fetchall()
|
|
575
|
+
)
|
|
576
|
+
if not affected:
|
|
577
|
+
self.conn.commit()
|
|
578
|
+
return 0
|
|
579
|
+
for row in affected:
|
|
580
|
+
self._assert_subject_writable_locked(
|
|
581
|
+
self._subject_ref_from_profile_row(row)
|
|
582
|
+
)
|
|
583
|
+
ids = [r["profile_id"] for r in affected]
|
|
584
|
+
ph = ",".join("?" * len(ids))
|
|
585
|
+
cur = self.conn.execute(
|
|
586
|
+
f"UPDATE profiles SET status = ?, retired_at = ?, last_modified_timestamp = ? " # noqa: S608
|
|
587
|
+
f"WHERE profile_id IN ({ph}) AND status IS NULL",
|
|
588
|
+
[Status.EXPIRED.value, now, now, *ids],
|
|
589
|
+
)
|
|
590
|
+
for row in affected:
|
|
591
|
+
_append_event_stmt(
|
|
592
|
+
self.conn,
|
|
593
|
+
org_id=self.org_id,
|
|
594
|
+
entity_type="profile",
|
|
595
|
+
entity_id=str(row["profile_id"]),
|
|
596
|
+
op="status_change",
|
|
597
|
+
prov="wasInvalidatedBy",
|
|
598
|
+
source_ids=[],
|
|
599
|
+
actor="system",
|
|
600
|
+
request_id=batch_request_id,
|
|
601
|
+
reason="ttl-expired",
|
|
602
|
+
from_status=None,
|
|
603
|
+
to_status=Status.EXPIRED.value,
|
|
604
|
+
status_namespace="lifecycle_status",
|
|
605
|
+
)
|
|
606
|
+
except Exception:
|
|
607
|
+
self.conn.rollback()
|
|
608
|
+
raise
|
|
609
|
+
else:
|
|
610
|
+
self.conn.commit()
|
|
611
|
+
return cur.rowcount
|
|
612
|
+
|
|
613
|
+
@SQLiteStorageBase.handle_exceptions
|
|
614
|
+
def get_profiles_by_ids(
|
|
615
|
+
self,
|
|
616
|
+
user_id: str,
|
|
617
|
+
profile_ids: list[str],
|
|
618
|
+
status_filter: list[Status | None] | None = None,
|
|
619
|
+
) -> list[UserProfile]:
|
|
620
|
+
if not profile_ids:
|
|
621
|
+
return []
|
|
622
|
+
if status_filter is None:
|
|
623
|
+
status_filter = [None]
|
|
624
|
+
current_ts = _epoch_now()
|
|
625
|
+
frag, sparams = _build_status_sql(status_filter)
|
|
626
|
+
ph = ",".join("?" for _ in profile_ids)
|
|
627
|
+
sql = (
|
|
628
|
+
f"SELECT * FROM profiles "
|
|
629
|
+
f"WHERE user_id = ? AND profile_id IN ({ph}) "
|
|
630
|
+
f"AND expiration_timestamp >= ? AND {frag}"
|
|
631
|
+
)
|
|
632
|
+
params: list[Any] = [user_id, *profile_ids, current_ts, *sparams]
|
|
633
|
+
return [_row_to_profile(r) for r in self._fetchall(sql, params)]
|
|
634
|
+
|
|
635
|
+
@SQLiteStorageBase.handle_exceptions
|
|
636
|
+
def get_profile_by_id(
|
|
637
|
+
self, profile_id: str, *, include_tombstones: bool = False
|
|
638
|
+
) -> UserProfile | None:
|
|
639
|
+
"""Fetch a single profile by primary key.
|
|
640
|
+
|
|
641
|
+
Args:
|
|
642
|
+
profile_id: The profile's primary key.
|
|
643
|
+
include_tombstones: When False (default), MERGED/SUPERSEDED/EXPIRED profiles
|
|
644
|
+
return None. Set to True for lineage resolution (resolve_current).
|
|
645
|
+
|
|
646
|
+
Returns:
|
|
647
|
+
The UserProfile if found and not filtered, otherwise None.
|
|
648
|
+
"""
|
|
649
|
+
sql = "SELECT * FROM profiles WHERE profile_id = ?"
|
|
650
|
+
if not include_tombstones:
|
|
651
|
+
ph = ",".join("?" * len(_PROFILE_TOMBSTONE_STATUS_VALUES))
|
|
652
|
+
sql += f" AND (status IS NULL OR status NOT IN ({ph}))"
|
|
653
|
+
row = self._fetchone(sql, (profile_id, *_PROFILE_TOMBSTONE_STATUS_VALUES))
|
|
654
|
+
else:
|
|
655
|
+
row = self._fetchone(sql, (profile_id,))
|
|
656
|
+
return _row_to_profile(row) if row else None
|
|
657
|
+
|
|
658
|
+
@SQLiteStorageBase.handle_exceptions
|
|
659
|
+
def get_distinct_generated_from_request_ids(self) -> list[str]:
|
|
660
|
+
"""Return DISTINCT non-empty generated_from_request_id values, including tombstones.
|
|
661
|
+
|
|
662
|
+
Returns:
|
|
663
|
+
list[str]: Distinct non-empty ``generated_from_request_id`` values.
|
|
664
|
+
"""
|
|
665
|
+
rows = self._fetchall(
|
|
666
|
+
"SELECT DISTINCT generated_from_request_id FROM profiles"
|
|
667
|
+
" WHERE generated_from_request_id IS NOT NULL"
|
|
668
|
+
" AND generated_from_request_id != ''",
|
|
669
|
+
(),
|
|
670
|
+
)
|
|
671
|
+
return [row[0] for row in rows]
|
|
672
|
+
|
|
673
|
+
@SQLiteStorageBase.handle_exceptions
|
|
674
|
+
def get_profiles_by_generated_from_request_id(
|
|
675
|
+
self,
|
|
676
|
+
request_id: str,
|
|
677
|
+
) -> list[UserProfile]:
|
|
678
|
+
"""Return all profiles for a generated_from_request_id, including tombstones.
|
|
679
|
+
|
|
680
|
+
Args:
|
|
681
|
+
request_id (str): The generated_from_request_id to filter on.
|
|
682
|
+
|
|
683
|
+
Returns:
|
|
684
|
+
list[UserProfile]: All matching profiles (any status).
|
|
685
|
+
"""
|
|
686
|
+
rows = self._fetchall(
|
|
687
|
+
"SELECT * FROM profiles WHERE generated_from_request_id = ?",
|
|
688
|
+
(request_id,),
|
|
689
|
+
)
|
|
690
|
+
return [_row_to_profile(r) for r in rows]
|
|
691
|
+
|
|
692
|
+
def get_all_generated_profiles(self) -> list[UserProfile]:
|
|
693
|
+
"""All profiles (any status) with a non-empty generated_from_request_id."""
|
|
694
|
+
rows = self._fetchall(
|
|
695
|
+
"SELECT * FROM profiles "
|
|
696
|
+
"WHERE generated_from_request_id IS NOT NULL "
|
|
697
|
+
"AND generated_from_request_id <> ''",
|
|
698
|
+
)
|
|
699
|
+
return [_row_to_profile(r) for r in rows]
|
|
700
|
+
|
|
701
|
+
@SQLiteStorageBase.handle_exceptions
|
|
702
|
+
def archive_profile_by_id(self, user_id: str, profile_id: str) -> bool:
|
|
703
|
+
with self._lock:
|
|
704
|
+
if (
|
|
705
|
+
self._assert_profile_writable_locked(profile_id, user_id=user_id)
|
|
706
|
+
is None
|
|
707
|
+
):
|
|
708
|
+
return False
|
|
709
|
+
now_ts = _epoch_now()
|
|
710
|
+
cur = self.conn.execute(
|
|
711
|
+
"UPDATE profiles SET status = ?, last_modified_timestamp = ?, retired_at = ? "
|
|
712
|
+
"WHERE profile_id = ? AND user_id = ? AND status IS NULL",
|
|
713
|
+
(Status.ARCHIVED.value, now_ts, now_ts, profile_id, user_id),
|
|
714
|
+
)
|
|
715
|
+
if cur.rowcount > 0:
|
|
716
|
+
_append_event_stmt(
|
|
717
|
+
self.conn,
|
|
718
|
+
org_id=self.org_id,
|
|
719
|
+
entity_type="profile",
|
|
720
|
+
entity_id=str(profile_id),
|
|
721
|
+
op="status_change",
|
|
722
|
+
prov="wasInvalidatedBy",
|
|
723
|
+
source_ids=[],
|
|
724
|
+
actor="api",
|
|
725
|
+
request_id=uuid.uuid4().hex,
|
|
726
|
+
reason="None->archived",
|
|
727
|
+
from_status=None,
|
|
728
|
+
to_status="archived",
|
|
729
|
+
status_namespace="lifecycle_status",
|
|
730
|
+
)
|
|
731
|
+
self.conn.commit()
|
|
732
|
+
return cur.rowcount > 0
|
|
733
|
+
|
|
734
|
+
@SQLiteStorageBase.handle_exceptions
|
|
735
|
+
def supersede_profiles_by_ids(
|
|
736
|
+
self,
|
|
737
|
+
user_id: str,
|
|
738
|
+
profile_ids: list[str],
|
|
739
|
+
request_id: str,
|
|
740
|
+
) -> list[str]:
|
|
741
|
+
"""Soft-delete profiles by setting status to SUPERSEDED, emitting set-based lineage.
|
|
742
|
+
|
|
743
|
+
For each matching id (user_id scoped, currently CURRENT), updates status to
|
|
744
|
+
SUPERSEDED and emits one ``status_change`` event under the shared ``request_id``.
|
|
745
|
+
Atomic: one ``conn.commit()`` at the end, guarded on rowcount per id.
|
|
746
|
+
FTS/vec rows are NOT removed — reads exclude tombstones by status filter.
|
|
747
|
+
|
|
748
|
+
Args:
|
|
749
|
+
user_id (str): Owning user id.
|
|
750
|
+
profile_ids (list[str]): Profile ids to supersede.
|
|
751
|
+
request_id (str): Shared request id for all emitted lineage events.
|
|
752
|
+
|
|
753
|
+
Returns:
|
|
754
|
+
list[str]: The profile ids actually superseded by this call, in input order
|
|
755
|
+
(already-superseded or absent ids are omitted).
|
|
756
|
+
"""
|
|
757
|
+
if not profile_ids:
|
|
758
|
+
return []
|
|
759
|
+
if not request_id:
|
|
760
|
+
raise ValueError("request_id must be non-empty for supersede")
|
|
761
|
+
now_ts = _epoch_now()
|
|
762
|
+
# Eligibility: CURRENT (NULL) or PENDING — the two live statuses dedup can target.
|
|
763
|
+
eligible = (None, Status.PENDING.value)
|
|
764
|
+
committed_ids: list[str] = []
|
|
765
|
+
with self._lock:
|
|
766
|
+
for pid in profile_ids:
|
|
767
|
+
# Read current status for from_status derivation (user_id scoped)
|
|
768
|
+
row = self.conn.execute(
|
|
769
|
+
"SELECT status, user_id, governance_subject_ref FROM profiles WHERE profile_id = ? AND user_id = ?",
|
|
770
|
+
(pid, user_id),
|
|
771
|
+
).fetchone()
|
|
772
|
+
if row is None:
|
|
773
|
+
continue
|
|
774
|
+
self._assert_subject_writable_locked(
|
|
775
|
+
self._subject_ref_from_profile_row(row)
|
|
776
|
+
)
|
|
777
|
+
old_status_val = (
|
|
778
|
+
row[0] if isinstance(row, (tuple, list)) else row["status"]
|
|
779
|
+
)
|
|
780
|
+
if old_status_val not in eligible:
|
|
781
|
+
continue
|
|
782
|
+
cur = self.conn.execute(
|
|
783
|
+
"UPDATE profiles SET status = ?, last_modified_timestamp = ?, retired_at = ? "
|
|
784
|
+
"WHERE profile_id = ? AND user_id = ? "
|
|
785
|
+
"AND (status IS NULL OR status = ?)",
|
|
786
|
+
(
|
|
787
|
+
Status.SUPERSEDED.value,
|
|
788
|
+
now_ts,
|
|
789
|
+
now_ts,
|
|
790
|
+
pid,
|
|
791
|
+
user_id,
|
|
792
|
+
Status.PENDING.value,
|
|
793
|
+
),
|
|
794
|
+
)
|
|
795
|
+
if cur.rowcount > 0:
|
|
796
|
+
_append_event_stmt(
|
|
797
|
+
self.conn,
|
|
798
|
+
org_id=self.org_id,
|
|
799
|
+
entity_type="profile",
|
|
800
|
+
entity_id=str(pid),
|
|
801
|
+
op="status_change",
|
|
802
|
+
prov="wasInvalidatedBy",
|
|
803
|
+
source_ids=[],
|
|
804
|
+
actor="dedup",
|
|
805
|
+
request_id=request_id,
|
|
806
|
+
reason=f"{old_status_val}->superseded",
|
|
807
|
+
from_status=old_status_val,
|
|
808
|
+
to_status=Status.SUPERSEDED.value,
|
|
809
|
+
status_namespace="lifecycle_status",
|
|
810
|
+
)
|
|
811
|
+
committed_ids.append(pid)
|
|
812
|
+
self.conn.commit()
|
|
813
|
+
return committed_ids
|
|
814
|
+
|
|
815
|
+
@SQLiteStorageBase.handle_exceptions
|
|
816
|
+
def delete_all_profiles_by_status(self, status: Status) -> int:
|
|
817
|
+
# Atomic: fts + vec + row + lineage in ONE lock/commit — rowid reuse race
|
|
818
|
+
# prevention (see delete_user_profile comment, #196).
|
|
819
|
+
batch_request_id = uuid.uuid4().hex
|
|
820
|
+
with self._lock:
|
|
821
|
+
rows = self.conn.execute(
|
|
822
|
+
"SELECT rowid, profile_id FROM profiles WHERE status = ?",
|
|
823
|
+
(status.value,),
|
|
824
|
+
).fetchall()
|
|
825
|
+
if not rows:
|
|
826
|
+
return 0
|
|
827
|
+
pids = [r["profile_id"] for r in rows]
|
|
828
|
+
rowids = [r["rowid"] for r in rows]
|
|
829
|
+
self._delete_in_chunks("profiles_fts", "profile_id", pids)
|
|
830
|
+
if self._has_sqlite_vec and rowids:
|
|
831
|
+
self._delete_in_chunks("profiles_vec", "rowid", rowids)
|
|
832
|
+
ph = ",".join("?" for _ in pids)
|
|
833
|
+
cur = self.conn.execute(
|
|
834
|
+
f"DELETE FROM profiles WHERE profile_id IN ({ph})",
|
|
835
|
+
pids, # noqa: S608
|
|
836
|
+
)
|
|
837
|
+
for pid in pids:
|
|
838
|
+
_emit_hard_delete_profile(
|
|
839
|
+
self.conn,
|
|
840
|
+
org_id=self.org_id,
|
|
841
|
+
entity_id=str(pid),
|
|
842
|
+
request_id=batch_request_id,
|
|
843
|
+
)
|
|
844
|
+
self.conn.commit()
|
|
845
|
+
return cur.rowcount
|
|
846
|
+
|
|
847
|
+
@SQLiteStorageBase.handle_exceptions
|
|
848
|
+
def get_user_ids_with_status(self, status: Status | None) -> list[str]:
|
|
849
|
+
if status is None or (hasattr(status, "value") and status.value is None):
|
|
850
|
+
rows = self._fetchall(
|
|
851
|
+
"SELECT DISTINCT user_id FROM profiles WHERE status IS NULL"
|
|
852
|
+
)
|
|
853
|
+
else:
|
|
854
|
+
rows = self._fetchall(
|
|
855
|
+
"SELECT DISTINCT user_id FROM profiles WHERE status = ?",
|
|
856
|
+
(status.value,),
|
|
857
|
+
)
|
|
858
|
+
return [r["user_id"] for r in rows]
|
|
859
|
+
|
|
860
|
+
@SQLiteStorageBase.handle_exceptions
|
|
861
|
+
def delete_profiles_by_ids(
|
|
862
|
+
self, profile_ids: list[str], *, emit_hard_delete: bool = True
|
|
863
|
+
) -> int:
|
|
864
|
+
if not profile_ids:
|
|
865
|
+
return 0
|
|
866
|
+
# Atomic: fts + vec + row + lineage in ONE lock/commit — rowid reuse race
|
|
867
|
+
# prevention (see delete_user_profile comment, #196).
|
|
868
|
+
ph = ",".join("?" for _ in profile_ids)
|
|
869
|
+
batch_request_id = uuid.uuid4().hex
|
|
870
|
+
with self._lock:
|
|
871
|
+
pre_rows = self.conn.execute(
|
|
872
|
+
f"SELECT rowid, profile_id FROM profiles WHERE profile_id IN ({ph})",
|
|
873
|
+
profile_ids,
|
|
874
|
+
).fetchall()
|
|
875
|
+
if not pre_rows:
|
|
876
|
+
return 0
|
|
877
|
+
existing = [r["profile_id"] for r in pre_rows]
|
|
878
|
+
rowids = [r["rowid"] for r in pre_rows]
|
|
879
|
+
self._delete_in_chunks("profiles_fts", "profile_id", existing)
|
|
880
|
+
if self._has_sqlite_vec and rowids:
|
|
881
|
+
self._delete_in_chunks("profiles_vec", "rowid", rowids)
|
|
882
|
+
cur = self.conn.execute(
|
|
883
|
+
f"DELETE FROM profiles WHERE profile_id IN ({ph})",
|
|
884
|
+
profile_ids, # noqa: S608
|
|
885
|
+
)
|
|
886
|
+
if emit_hard_delete:
|
|
887
|
+
for pid in existing:
|
|
888
|
+
_emit_hard_delete_profile(
|
|
889
|
+
self.conn,
|
|
890
|
+
org_id=self.org_id,
|
|
891
|
+
entity_id=str(pid),
|
|
892
|
+
request_id=batch_request_id,
|
|
893
|
+
actor="system",
|
|
894
|
+
)
|
|
895
|
+
self.conn.commit()
|
|
896
|
+
return cur.rowcount
|