Coverage for app / services / data_export.py: 99%
202 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2The user's copy of their data — UK and EU GDPR access and portability.
4``GET /app/users/me/export`` answers with one zip file holding:
6* ``data/<table>.json`` — every row the user owns, one file per table, each
7 row with every stored column (credentials withheld; see below);
8* ``memories.json`` — what agents remember from the user's conversations,
9 held by svc-ai rather than svc-core;
10* ``files/`` — the original documents the user uploaded to knowledge;
11* ``README.md`` — what each file holds, and what the export leaves out.
13What is exported is a registry rather than a walk of the user's resources:
14each table names how its rows are selected — the user's own row, rows the
15user owns or caused, or children of rows already exported — and
16``NOT_EXPORTED`` gives the reason for each table that is not.
17``tests/test_data_export.py`` fails on a table that is in neither, so a
18table added later has to be decided on rather than silently left out.
20Rows are serialised from every column rather than through the API's ``Read``
21schemas: a schema is what a page needs, and an export that quietly drops the
22fields no page shows is not a copy of the data. Columns that may hold
23credentials are withheld by the same rule the edit history uses
24(``history.credential_fields``) and marked as withheld rather than dropped,
25so the reader can see something was left out.
27Only resources the user owns directly are exported. Resources owned by a
28project or organisation belong to it, and copying them out would hand one
29member everything the others put there.
30"""
32from __future__ import annotations
34import base64
35import enum
36import json
37import logging
38import re
39import zipfile
40from abc import ABC, abstractmethod
41from collections.abc import Callable, Iterable, Iterator
42from dataclasses import dataclass, field
43from datetime import date, datetime
44from decimal import Decimal
45from types import SimpleNamespace
46from typing import IO, Any
47from uuid import UUID
49from sqlalchemy import ColumnElement, Select, Table, or_, select
50from sqlalchemy.orm import Session
52from app.db.postgres import models as m
53from app.services import ai_client
54from app.services.history import credential_fields
55from app.util import minio_client
56from app.util.time import aware_utcnow, utc_isoformat
58logger = logging.getLogger(__name__)
60#: Stands in for a column withheld because it may hold credentials.
61WITHHELD = "[withheld: may contain credentials]"
62#: In place of a column an export never carries (``ExportTable.hidden``).
63HIDDEN = "[withheld: an answer a governance rule withheld]"
66# ── How a table's rows are chosen ───────────────────────────────────────────
69class Selector(ABC):
70 """Which rows of a table belong in one user's export."""
72 @abstractmethod
73 def where(self, table: Table, user_id: UUID) -> ColumnElement[bool]: ...
76@dataclass(frozen=True)
77class OwnRow(Selector):
78 """The user's own record."""
80 def where(self, table: Table, user_id: UUID) -> ColumnElement[bool]:
81 return table.c.id == user_id
84@dataclass(frozen=True)
85class ByUser(Selector):
86 """Rows whose ``column`` names the user — what they own, ran or caused."""
88 column: str = "owner_user_id"
90 def where(self, table: Table, user_id: UUID) -> ColumnElement[bool]:
91 return table.c[self.column] == user_id
94@dataclass(frozen=True)
95class ChildOf(Selector):
96 """Rows that hang off rows of another exported table."""
98 parent: ExportTable
99 column: str
101 def where(self, table: Table, user_id: UUID) -> ColumnElement[bool]:
102 return table.c[self.column].in_(self.parent.ids(user_id))
105@dataclass(frozen=True)
106class HistoryOf(Selector):
107 """Edit history: every version of a resource the user owns, and every
108 version the user wrote of anything else. ``resource_versions`` refers to
109 its resource softly (no foreign key), so this is the one table selected
110 by id across many others."""
112 resources: tuple[ExportTable, ...]
114 def where(self, table: Table, user_id: UUID) -> ColumnElement[bool]:
115 return or_(
116 table.c.actor_user_id == user_id,
117 *(table.c.resource_id.in_(r.ids(user_id)) for r in self.resources),
118 )
121@dataclass(frozen=True)
122class ExportTable:
123 #: An ORM model, or the ``Table`` of a plain link table.
124 model: type | Table
125 selector: Selector
126 #: One line in the README saying what the file holds.
127 description: str
128 #: Columns never exported, marked as withheld like credentials: an
129 #: answer a rule withheld from the person exporting (``withheld_text``).
130 hidden: frozenset[str] = frozenset()
132 @property
133 def table(self) -> Table:
134 return self.model if isinstance(self.model, Table) else self.model.__table__
136 @property
137 def name(self) -> str:
138 return self.table.name
140 def ids(self, user_id: UUID) -> Select:
141 return select(self.table.c.id).where(self.selector.where(self.table, user_id))
143 def statement(self, user_id: UUID) -> Select:
144 t = self.table
145 if "created_at" in t.c:
146 order = [t.c.created_at, *t.primary_key.columns]
147 else:
148 order = list(t.primary_key.columns) or [next(iter(t.c))]
149 return select(t).where(self.selector.where(t, user_id)).order_by(*order)
152def _owned(model: type, description: str) -> ExportTable:
153 return ExportTable(model, ByUser(), description)
156def _child(
157 model: type | Table, parent: ExportTable, column: str, description: str
158) -> ExportTable:
159 return ExportTable(model, ChildOf(parent, column), description)
162def _link(name: str) -> Table:
163 return m.Base.metadata.tables[name]
166# ── The registry ────────────────────────────────────────────────────────────
168ACCOUNT = ExportTable(m.User, OwnRow(), "Your account: name, email address and status.")
169PROJECTS = _owned(m.Project, "Projects you own.")
170AGENTS = _owned(m.Agent, "Your agents and their configuration.")
171CONVERSATIONS = _owned(m.Conversation, "Your conversations.")
172MESSAGES = _child(
173 m.ChatMessage,
174 CONVERSATIONS,
175 "conversation_id",
176 "Every message in your conversations, yours and the agent's.",
177)
178KNOWLEDGE = _owned(m.Knowledge, "Your knowledge sources.")
179KNOWLEDGE_DOCUMENTS = _child(
180 m.KnowledgeDocument,
181 KNOWLEDGE,
182 "knowledge_id",
183 "Documents and web pages in your knowledge sources. Uploaded originals are in files/.",
184)
185REPOSITORIES = _owned(m.KnowledgeRepository, "Your knowledge repositories.")
186UPLOADED_FILES = _owned(
187 m.UploadedFile,
188 "Documents in your Personal library, with their text. Originals kept "
189 "since October 2026 are in files/uploads/. An organisation's or "
190 "project's are its own.",
191)
192SKILLS = _owned(m.Skill, "Your skills.")
193SKILLSETS = _owned(m.Skillset, "Your skillsets.")
194TOOLKITS = _owned(m.Toolkit, "Your toolkits.")
195EXPERIMENTS = _owned(m.Experiment, "Your evaluations (experiments).")
196DATASETS = _owned(m.TestSuite, "Your evaluation datasets.")
197WORLDS = _owned(m.SimulationWorld, "Your simulation worlds.")
198DASHBOARDS = _owned(m.Dashboard, "Your dashboards.")
199SWARMS = _owned(m.Swarm, "Your swarms: their shape, agents and defaults.")
200SWARM_RUNS = ExportTable(
201 m.SwarmRun,
202 ByUser("user_id"),
203 "Swarm runs you started, with each task, its plan and its answer.",
204)
206#: Resources the user owns, whose edit history comes with them.
207_OWNED_RESOURCES = (
208 PROJECTS,
209 AGENTS,
210 CONVERSATIONS,
211 KNOWLEDGE,
212 REPOSITORIES,
213 SKILLS,
214 SKILLSETS,
215 TOOLKITS,
216 EXPERIMENTS,
217 DATASETS,
218 WORLDS,
219 DASHBOARDS,
220 SWARMS,
221 _owned(m.CustomWorker, "Your workers."),
222 _owned(m.MCPServer, "Your MCP servers. Connection settings are withheld."),
223 _owned(m.Rule, "Your governance rules."),
224 UPLOADED_FILES,
225)
227EXPORT_TABLES: tuple[ExportTable, ...] = (
228 ACCOUNT,
229 ExportTable(
230 m.UserOrganisation,
231 ByUser("user_id"),
232 "Organisations you belong to, and your role in each.",
233 ),
234 ExportTable(
235 m.UserProject,
236 ByUser("user_id"),
237 "Projects you belong to, and your role in each.",
238 ),
239 *_OWNED_RESOURCES,
240 # What hangs off them.
241 _child(
242 _link("agent_industries"), AGENTS, "agent_id", "Industry tags on your agents."
243 ),
244 _child(_link("agent_roles"), AGENTS, "agent_id", "Role tags on your agents."),
245 _child(
246 m.AgentRepository,
247 AGENTS,
248 "agent_id",
249 "Knowledge repositories granted to your agents.",
250 ),
251 _child(m.AgentSkillset, AGENTS, "agent_id", "Skillsets granted to your agents."),
252 _child(m.AgentToolkit, AGENTS, "agent_id", "Toolkits granted to your agents."),
253 MESSAGES,
254 _child(
255 m.ChatMessageSegment,
256 MESSAGES,
257 "message_id",
258 "The parts of each agent reply, as it was streamed.",
259 ),
260 KNOWLEDGE_DOCUMENTS,
261 _child(
262 m.KnowledgeCrawl,
263 KNOWLEDGE,
264 "knowledge_id",
265 "Each crawl of your website sources.",
266 ),
267 _child(
268 m.KnowledgePageVersion,
269 KNOWLEDGE,
270 "knowledge_id",
271 "Each version of a crawled web page (the record, not the page).",
272 ),
273 _child(
274 m.RepositoryKnowledge,
275 REPOSITORIES,
276 "repository_id",
277 "Which sources each of your repositories holds.",
278 ),
279 _child(
280 m.SkillsetSkill,
281 SKILLSETS,
282 "skillset_id",
283 "Which skills each of your skillsets bundles.",
284 ),
285 _child(
286 m.ToolkitMCPServer,
287 TOOLKITS,
288 "toolkit_id",
289 "Which MCP servers each of your toolkits holds.",
290 ),
291 _child(
292 m.ExperimentVariant,
293 EXPERIMENTS,
294 "experiment_id",
295 "The variants each evaluation compares.",
296 ),
297 _child(
298 m.ExperimentBatch,
299 EXPERIMENTS,
300 "experiment_id",
301 "Each run of your evaluations, with its summary.",
302 ),
303 _child(
304 m.ExperimentRun,
305 EXPERIMENTS,
306 "experiment_id",
307 "Every answer and score in your evaluation runs.",
308 ),
309 _child(m.TestCase, DATASETS, "test_suite_id", "The cases in your datasets."),
310 _child(
311 m.SimulationScenario, WORLDS, "world_id", "Scenarios in your simulation worlds."
312 ),
313 _child(m.Simulation, WORLDS, "world_id", "Simulations run in your worlds."),
314 _child(
315 m.DashboardWidget, DASHBOARDS, "dashboard_id", "The tiles on your dashboards."
316 ),
317 # What the user ran or caused.
318 ExportTable(
319 m.SkillRun,
320 ByUser("user_id"),
321 "Skills you ran on their own, with their inputs and outputs.",
322 ),
323 ExportTable(
324 m.ScenarioRun,
325 ByUser("user_id"),
326 "Scenario runs you started, with each file and what each turn did.",
327 ),
328 SWARM_RUNS,
329 _child(
330 m.SwarmTask,
331 SWARM_RUNS,
332 "run_id",
333 "Every task of your swarm runs: who did it, what it was asked, what "
334 "it wrote and what it cost.",
335 ),
336 ExportTable(
337 m.GenerationRun,
338 ByUser("actor_user_id"),
339 "Each time you had CHAIN-R generate something, with what you asked for.",
340 ),
341 ExportTable(
342 m.GovernanceUsage,
343 ByUser(),
344 "Your usage ledger: every model call, its tokens and cost.",
345 ),
346 ExportTable(
347 m.GovernanceEvent, ByUser(), "What each governance rule did on your requests."
348 ),
349 ExportTable(
350 m.KnowledgeCitation,
351 ByUser(),
352 "Which knowledge sources the answers you were given cited.",
353 ),
354 ExportTable(
355 m.KnowledgeTurn,
356 ByUser(),
357 "What each of your answers asked of its agent's knowledge, and what it "
358 "lacked: the request as searched (redacted), the gaps its quality check "
359 "found, and the web sites it cited.",
360 ),
361 ExportTable(
362 m.KnowledgeRetrieval,
363 ByUser(),
364 "What each knowledge source gave each of your answers: passages found, "
365 "kept and ruled out.",
366 ),
367 ExportTable(
368 m.KnowledgeRecommendationDismissal,
369 ByUser("dismissed_by_user_id"),
370 "The knowledge recommendations you set aside, and when.",
371 ),
372 ExportTable(
373 m.ReviewFlag,
374 ByUser(),
375 "Responses your audit rules flagged for review.",
376 # An answer withheld from you stays withheld (``review.record_withheld``).
377 hidden=frozenset({"withheld_text"}),
378 ),
379 ExportTable(
380 m.DecisionOutcome,
381 ByUser(),
382 "Verdicts given on your answers and runs: accepted, edited (with the correction) or rejected.",
383 ),
384 ExportTable(
385 m.DecisionReadLog,
386 ByUser(),
387 "Each time a reviewer opened the decision record of one of your answers or runs.",
388 ),
389 ExportTable(
390 m.BackgroundEvent,
391 ByUser(),
392 "Background work done for you: tile refreshes, crawls.",
393 ),
394 ExportTable(
395 m.Notification,
396 ByUser("recipient_user_id"),
397 "Your inbox: the alerts and notices CHAIN-R sent you.",
398 ),
399 ExportTable(
400 m.SpendStatement,
401 ByUser(),
402 "Your Personal workspace's monthly statements: spend, budgets and "
403 "governance, aggregate figures only. An organisation's or project's "
404 "statements are theirs.",
405 ),
406 ExportTable(
407 m.ResourceVersion,
408 HistoryOf(_OWNED_RESOURCES),
409 "The edit history of your resources, and every change you made to anything.",
410 ),
411)
413#: Tables deliberately not exported, and why.
414NOT_EXPORTED: dict[str, str] = {
415 "organisations": "Belongs to the organisation. Your memberships are in user_organisations.",
416 "roles": "The platform's role definitions, the same for everyone.",
417 "permissions": "The platform's permission definitions, the same for everyone.",
418 "role_permissions": "The platform's role definitions, the same for everyone.",
419 "resource_industries": "The shared tag vocabulary. Your agents' tags are in agent_industries.",
420 "resource_roles": "The shared tag vocabulary. Your agents' tags are in agent_roles.",
421 "agent_memory": "Unused. Agent memories are held by the AI service and exported as memories.json.",
422 "scheduled_jobs": "The platform's own background job state.",
423 "membership_invites": "Invitations belong to the organisation and name the people invited. Your memberships are in user_organisations.",
424 "workspace_inheritance": "What a project inherits belongs to the project, and only your own work is exported.",
425}
428# ── Rows to JSON ────────────────────────────────────────────────────────────
431def json_value(value: Any) -> Any:
432 """A column value as JSON — timestamps with their offset, like the API."""
433 if isinstance(value, datetime):
434 return utc_isoformat(value)
435 if isinstance(value, date):
436 return value.isoformat()
437 if isinstance(value, UUID):
438 return str(value)
439 if isinstance(value, enum.Enum):
440 return value.value
441 if isinstance(value, Decimal):
442 return str(value)
443 if isinstance(value, bytes):
444 return base64.b64encode(value).decode("ascii")
445 return value
448def serialise_row(spec: ExportTable, row: dict[str, Any]) -> dict[str, Any]:
449 """Every column of ``row``, credentials withheld."""
450 credentials = (
451 set()
452 if isinstance(spec.model, Table)
453 else credential_fields(spec.model, SimpleNamespace(**row))
454 )
456 def value_of(key: str, value: Any) -> Any:
457 if value is None:
458 return None
459 if key in spec.hidden:
460 return HIDDEN
461 if key in credentials:
462 return WITHHELD
463 return json_value(value)
465 return {key: value_of(key, value) for key, value in row.items()}
468# ── Collecting ──────────────────────────────────────────────────────────────
471@dataclass(frozen=True)
472class StoredFile:
473 """An uploaded original to copy into the zip."""
475 object_name: str
476 path: str
479@dataclass
480class ExportSummary:
481 rows: dict[str, int] = field(default_factory=dict)
482 files: int = 0
483 missing_files: list[str] = field(default_factory=list)
484 memories: int | None = None
487def iter_tables(db: Session, user_id: UUID) -> Iterator[tuple[ExportTable, list[dict]]]:
488 """Each exported table with the user's rows, one table at a time."""
489 for spec in EXPORT_TABLES:
490 rows = db.execute(spec.statement(user_id)).mappings().all()
491 yield spec, [serialise_row(spec, dict(r)) for r in rows]
494_UNSAFE = re.compile(r"[^\w.\- ]+")
497def _safe_filename(name: str) -> str:
498 """A filename that cannot climb out of its folder when the zip is opened."""
499 base = name.replace("\\", "/").rsplit("/", 1)[-1]
500 cleaned = _UNSAFE.sub("_", base).strip(" .")
501 return cleaned[:150] or "file"
504def stored_files(
505 documents: Iterable[dict], uploads: Iterable[dict] = ()
506) -> list[StoredFile]:
507 """The uploaded originals behind knowledge documents and chat uploads. A
508 web page has no stored original — its versions are fetched copies, not
509 the user's — and nor has an upload from before originals were kept, so
510 only rows with a stored object are listed."""
511 files = []
512 for upload in uploads:
513 if not upload.get("object_key"):
514 continue
515 name = _safe_filename(upload.get("name") or "file")
516 files.append(
517 StoredFile(upload["object_key"], f"files/uploads/{upload['id']}_{name}")
518 )
519 for doc in documents:
520 meta = doc.get("document_metadata") or {}
521 obj = meta.get("minio_object") if isinstance(meta, dict) else None
522 if not obj:
523 continue
524 name = _safe_filename(
525 meta.get("original_filename") or doc.get("source_id") or "file"
526 )
527 files.append(
528 StoredFile(obj, f"files/knowledge/{doc['knowledge_id']}/{doc['id']}_{name}")
529 )
530 return files
533# ── Writing ─────────────────────────────────────────────────────────────────
536def _dump(value: Any) -> bytes:
537 return json.dumps(value, indent=2, ensure_ascii=False, default=json_value).encode()
540def write_export(
541 out: IO[bytes],
542 *,
543 tables: Iterable[tuple[ExportTable, list[dict]]],
544 memories: list[dict] | None,
545 read_file: Callable[[str], Iterable[bytes]],
546 exported_at: datetime,
547) -> ExportSummary:
548 """Write the zip to ``out``. Pure apart from ``read_file``, so the
549 layout is testable without a database or object store."""
550 summary = ExportSummary()
551 documents: list[dict] = []
552 uploads: list[dict] = []
553 with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as zf:
554 for spec, rows in tables:
555 zf.writestr(f"data/{spec.name}.json", _dump(rows))
556 summary.rows[spec.name] = len(rows)
557 if spec.name == KNOWLEDGE_DOCUMENTS.name:
558 documents = rows
559 elif spec.name == UPLOADED_FILES.name:
560 uploads = rows
562 if memories is not None:
563 zf.writestr("memories.json", _dump(memories))
564 summary.memories = len(memories)
566 for f in stored_files(documents, uploads):
567 try:
568 # Opened before the entry is: a missing object then leaves no
569 # empty file behind in the zip, only a line in the README.
570 chunks = read_file(f.object_name)
571 with zf.open(f.path, "w") as dest:
572 for chunk in chunks:
573 dest.write(chunk)
574 summary.files += 1
575 except Exception:
576 logger.exception("Export could not read stored file %s", f.object_name)
577 summary.missing_files.append(f.path)
579 zf.writestr("README.md", readme(summary, exported_at))
580 return summary
583def readme(summary: ExportSummary, exported_at: datetime) -> str:
584 lines = [
585 "# Your CHAIN-R data",
586 "",
587 f"Exported {utc_isoformat(exported_at)}. Timestamps are UTC, with their offset.",
588 "",
589 "## What is here",
590 "",
591 "Each file in `data/` is a JSON list of rows, with every stored column.",
592 "Rows refer to each other by `id`.",
593 "",
594 "| File | Rows | What it holds |",
595 "|---|---:|---|",
596 ]
597 for spec in EXPORT_TABLES:
598 lines.append(
599 f"| `data/{spec.name}.json` | {summary.rows.get(spec.name, 0)} | {spec.description} |"
600 )
601 lines += [
602 "",
603 (
604 f"`memories.json` holds {summary.memories} memories agents keep from your conversations."
605 if summary.memories is not None
606 else "**Agent memories could not be fetched.** Export again to include them."
607 ),
608 "",
609 f"`files/` holds {summary.files} documents you uploaded: to knowledge in "
610 "`files/knowledge/`, by source and document id, and to chats in "
611 "`files/uploads/`, by document id.",
612 ]
613 if summary.missing_files:
614 lines += [
615 "",
616 "**These uploaded files could not be read, and are missing:**",
617 "",
618 ]
619 lines += [f"- `{p}`" for p in summary.missing_files]
620 lines += [
621 "",
622 "## What is not here",
623 "",
624 f"- Columns that may hold credentials (database connection details, MCP server keys) read `{WITHHELD}`.",
625 "- Resources owned by a project or organisation rather than by you. They belong to it.",
626 "- Sign-in records and sessions, which the Security tab in Settings shows.",
627 "- The platform's operational logs and traces.",
628 "",
629 "For anything else, email help@datachainr.com.",
630 "",
631 ]
632 return "\n".join(lines)
635# ── Entry point ─────────────────────────────────────────────────────────────
638def _read_object(object_name: str) -> Iterator[bytes]:
639 """Open a stored object and stream it. Opening is eager — a missing
640 object raises here, before the caller starts a zip entry for it."""
641 return minio_client.stream(object_name)
644def build_export(db: Session, user: m.User, out: IO[bytes]) -> ExportSummary:
645 """Write ``user``'s export to ``out``.
647 An unreachable svc-ai or a missing stored file leaves a gap the README
648 names rather than failing the export: most of the data is still the
649 user's to have, and a request that fails outright tells them nothing.
650 """
651 try:
652 memories = ai_client.list_user_memory(str(user.id))
653 except ai_client.AIServiceError:
654 logger.warning("Export for user %s could not fetch agent memories", user.id)
655 memories = None
656 summary = write_export(
657 out,
658 tables=iter_tables(db, user.id),
659 memories=memories,
660 read_file=_read_object,
661 exported_at=aware_utcnow(),
662 )
663 logger.info(
664 "Exported data for user %s: %d rows, %d files, %d missing, memories %s",
665 user.id,
666 sum(summary.rows.values()),
667 summary.files,
668 len(summary.missing_files),
669 summary.memories,
670 )
671 return summary