From f19ba0c79843e67f3b43c08ef8ca47bca2087489 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sun, 6 Dec 2026 10:50:23 -0500 Subject: [PATCH] fix(8822): the backup converts each table as it reads it and streams each section to disk The export held every table's ORM objects and every table's rows at once, and the archive writer then built each section as one byte string (a peak of twice the section). The nightly run raised the app's memory about 200 MB that it kept. Each table is now converted before the next is read, and each section is encoded into a spool file that moves to disk past 1 MB. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/services/backup.py | 253 ++++++++++++++------------- src/grimoire/services/backup_file.py | 31 ++-- tests/test_services_backup_file.py | 19 ++ 3 files changed, 169 insertions(+), 134 deletions(-) diff --git a/src/grimoire/services/backup.py b/src/grimoire/services/backup.py index 389d6c6f..f1b4c095 100644 --- a/src/grimoire/services/backup.py +++ b/src/grimoire/services/backup.py @@ -1083,93 +1083,152 @@ async def export_full_backup() -> dict: """ from grimoire.services.instance import get_instance_id + # Each table is converted to its rows as soon as it is read, so its ORM + # objects are released before the next table arrives. Read all at once and + # converted at the end, every table's objects and every table's rows were + # alive together, and the app keeps the memory of its largest moment. async with async_session() as session: + async def rows(stmt, to_rows): + return to_rows((await session.execute(stmt)).scalars().all()) + + async def tuples(stmt, to_rows): + return to_rows((await session.execute(stmt)).all()) + instance_id = await get_instance_id(session) - users =(await session.execute(select(User).order_by(User.id))).scalars().all() - projects = (await session.execute(select(Project).order_by(Project.id))).scalars().all() - milestones = (await session.execute(select(Milestone).order_by(Milestone.id))).scalars().all() - notes = (await session.execute(select(Note).order_by(Note.id))).scalars().all() - task_logs = (await session.execute(select(TaskLog).order_by(TaskLog.id))).scalars().all() - note_drafts = (await session.execute(select(NoteDraft).order_by(NoteDraft.id))).scalars().all() - note_versions = (await session.execute( - select(NoteVersion).order_by(NoteVersion.note_id, NoteVersion.id) - )).scalars().all() - rule_versions = (await session.execute( - select(RuleVersion).order_by(RuleVersion.rule_id, RuleVersion.id) - )).scalars().all() - settings = (await session.execute(select(Setting).order_by(Setting.user_id, Setting.key))).scalars().all() - systems = (await session.execute(select(System).order_by(System.id))).scalars().all() + out = { + "version": BACKUP_VERSION, + "scope": "full", + "instance_id": instance_id, + "exported_at": datetime.now(timezone.utc).isoformat(), + "_security_notice": ( + "This backup contains hashed passwords. " + "Store it securely and restrict access." + ), + "_not_included": _NOT_INCLUDED, + } + out["users"] = await rows(select(User).order_by(User.id), _user_rows) + out["projects"] = await rows(select(Project).order_by(Project.id), _project_rows) + out["milestones"] = await rows(select(Milestone).order_by(Milestone.id), _milestone_rows) + out["notes"] = await rows(select(Note).order_by(Note.id), _note_rows) + out["task_logs"] = await rows(select(TaskLog).order_by(TaskLog.id), _task_log_rows) + out["note_drafts"] = await rows(select(NoteDraft).order_by(NoteDraft.id), _note_draft_rows) + out["note_versions"] = await rows( + select(NoteVersion).order_by(NoteVersion.note_id, NoteVersion.id), + _note_version_rows, + ) + out["rule_versions"] = await rows( + select(RuleVersion).order_by(RuleVersion.rule_id, RuleVersion.id), + _rule_version_rows, + ) + out["settings"] = await rows( + select(Setting).order_by(Setting.user_id, Setting.key), _setting_rows, + ) + out["rulebooks"] = await rows(select(Rulebook).order_by(Rulebook.id), _rulebook_rows) + out["rulebook_topics"] = await rows(select(RulebookTopic).order_by(RulebookTopic.id), _topic_rows) + out["rules"] = await rows(select(Rule).order_by(Rule.id), _rule_rows) + # Kept as objects: the Systems below name their canonical system by slug. canonical_systems = (await session.execute( select(CanonicalSystem).where(CanonicalSystem.deleted_at.is_(None)) .order_by(CanonicalSystem.order_index, CanonicalSystem.id) )).scalars().all() - rule_system_rows = (await session.execute( + out["canonical_systems"] = _canonical_system_rows(canonical_systems) + out["rule_systems"] = await tuples( select(rule_systems_t.c.rule_id, CanonicalSystem.slug) .join(CanonicalSystem, CanonicalSystem.id == rule_systems_t.c.canonical_id) - .order_by(rule_systems_t.c.rule_id, CanonicalSystem.slug) - )).all() - rule_moment_rows = (await session.execute( + .order_by(rule_systems_t.c.rule_id, CanonicalSystem.slug), + _rule_system_rows, + ) + out["rule_moments"] = await tuples( select(rule_moments_t.c.rule_id, rule_moments_t.c.moment) - .order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment) - )).all() - rule_trigger_rows = (await session.execute( + .order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment), + _rule_moment_rows, + ) + out["rule_triggers"] = await tuples( select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind, rule_triggers_t.c.pattern, rule_triggers_t.c.moment) .order_by(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind, - rule_triggers_t.c.pattern, rule_triggers_t.c.moment) - )).all() - rule_moment_judgments = (await session.execute( - select(RuleMomentJudgment).order_by(RuleMomentJudgment.id) - )).scalars().all() - rule_field_judgments = (await session.execute( - select(RuleFieldJudgment).order_by(RuleFieldJudgment.id) - )).scalars().all() - rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all() - lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all() - lesson_no_rule = (await session.execute(select(LessonNoRule).order_by(LessonNoRule.lesson_id))).scalars().all() - lesson_situations = (await session.execute(select(LessonSituation).order_by(LessonSituation.id))).scalars().all() - record_systems = (await session.execute(select(RecordSystem).order_by(RecordSystem.id))).scalars().all() - supersessions = ( - await session.execute(select(NoteSupersession).order_by(NoteSupersession.id)) - ).scalars().all() + rule_triggers_t.c.pattern, rule_triggers_t.c.moment), + _rule_trigger_rows, + ) + out["rule_moment_judgments"] = await rows( + select(RuleMomentJudgment).order_by(RuleMomentJudgment.id), + _rule_moment_judgment_rows, + ) + out["rule_field_judgments"] = await rows( + select(RuleFieldJudgment).order_by(RuleFieldJudgment.id), + _rule_field_judgment_rows, + ) + out["rule_relations"] = await rows( + select(RuleRelation).order_by(RuleRelation.id), _rule_relation_rows, + ) + out["lesson_rule_links"] = await rows( + select(LessonRuleLink).order_by(LessonRuleLink.id), _lesson_rule_link_rows, + ) + out["lesson_no_rule"] = await rows( + select(LessonNoRule).order_by(LessonNoRule.lesson_id), _lesson_no_rule_rows, + ) + out["lesson_situations"] = await rows( + select(LessonSituation).order_by(LessonSituation.id), _lesson_situation_rows, + ) + canonical_slugs = {c.id: c.slug for c in canonical_systems} + out["systems"] = await rows( + select(System).order_by(System.id), + lambda systems: _system_rows(systems, canonical_slugs), + ) + out["record_systems"] = await rows( + select(RecordSystem).order_by(RecordSystem.id), _record_system_rows, + ) # Parent-first, so a restore can resolve parent_id as it goes rather # than needing a second pass — the self-FK is the only ordering # constraint in this payload. - design_systems = (await session.execute( + out["design_systems"] = await rows( select(DesignSystem).order_by(DesignSystem.parent_id.nullsfirst(), - DesignSystem.id) - )).scalars().all() - design_tokens = (await session.execute(select(DesignToken).order_by(DesignToken.id))).scalars().all() - usage_events = (await session.execute(select(NoteUsageEvent).order_by(NoteUsageEvent.id))).scalars().all() - rule_usage_events = ( - await session.execute(select(RuleUsageEvent).order_by(RuleUsageEvent.id)) - ).scalars().all() - system_usage_events = ( - await session.execute(select(SystemUsageEvent).order_by(SystemUsageEvent.id)) - ).scalars().all() + DesignSystem.id), + _design_system_rows, + ) + out["design_tokens"] = await rows( + select(DesignToken).order_by(DesignToken.id), _design_token_rows, + ) + out["note_usage_events"] = await rows( + select(NoteUsageEvent).order_by(NoteUsageEvent.id), _usage_event_rows, + ) + out["rule_usage_events"] = await rows( + select(RuleUsageEvent).order_by(RuleUsageEvent.id), _rule_usage_event_rows, + ) + out["system_usage_events"] = await rows( + select(SystemUsageEvent).order_by(SystemUsageEvent.id), + _system_usage_event_rows, + ) # Oldest first, so a restored history reads in the order the dials # actually moved — the sequence IS the argument when a surface has been # walked up and down. - retrieval_tuning_events = (await session.execute( - select(RetrievalTuningEvent).order_by(RetrievalTuningEvent.id) - )).scalars().all() - moment_mappings = (await session.execute( - select(MomentMapping).order_by(MomentMapping.id) - )).scalars().all() - repo_bindings = (await session.execute(select(RepoBinding).order_by(RepoBinding.id))).scalars().all() - code_shapes = (await session.execute(select(CodeShape).order_by(CodeShape.id))).scalars().all() - code_shape_events = (await session.execute( - select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id) - )).scalars().all() - code_shape_guard_reviews = (await session.execute( - select(CodeShapeGuardReview).order_by(CodeShapeGuardReview.id) - )).scalars().all() - code_shape_uses = (await session.execute( - select(CodeShapeUse).order_by(CodeShapeUse.shape_id, CodeShapeUse.snippet_id, CodeShapeUse.id) - )).scalars().all() - rulebooks = (await session.execute(select(Rulebook).order_by(Rulebook.id))).scalars().all() - topics = (await session.execute(select(RulebookTopic).order_by(RulebookTopic.id))).scalars().all() - rules = (await session.execute(select(Rule).order_by(Rule.id))).scalars().all() + out["retrieval_tuning_events"] = await rows( + select(RetrievalTuningEvent).order_by(RetrievalTuningEvent.id), + _retrieval_tuning_event_rows, + ) + out["moment_mappings"] = await rows( + select(MomentMapping).order_by(MomentMapping.id), _moment_mapping_rows, + ) + out["repo_bindings"] = await rows( + select(RepoBinding).order_by(RepoBinding.id), _repo_binding_rows, + ) + out["note_supersessions"] = await rows( + select(NoteSupersession).order_by(NoteSupersession.id), + _note_supersession_rows, + ) + out["code_shapes"] = await rows(select(CodeShape).order_by(CodeShape.id), _code_shape_rows) + out["code_shape_events"] = await rows( + select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id), + _code_shape_event_rows, + ) + out["code_shape_uses"] = await rows( + select(CodeShapeUse).order_by(CodeShapeUse.shape_id, CodeShapeUse.snippet_id, CodeShapeUse.id), + _code_shape_use_rows, + ) + out["code_shape_guard_reviews"] = await rows( + select(CodeShapeGuardReview).order_by(CodeShapeGuardReview.id), + _code_shape_guard_review_rows, + ) platforms = (await session.execute( select(Platform).where(Platform.deleted_at.is_(None)) .order_by(Platform.order_index, Platform.id) @@ -1191,63 +1250,11 @@ async def export_full_backup() -> dict: family_decisions = (await session.execute( select(FamilyDecision).order_by(FamilyDecision.id) )).scalars().all() - - return { - "version": BACKUP_VERSION, - "scope": "full", - "instance_id": instance_id, - "exported_at": datetime.now(timezone.utc).isoformat(), - "_security_notice": ( - "This backup contains hashed passwords. " - "Store it securely and restrict access." - ), - "_not_included": _NOT_INCLUDED, - "users": _user_rows(users), - "projects": _project_rows(projects), - "milestones": _milestone_rows(milestones), - "notes": _note_rows(notes), - "task_logs": _task_log_rows(task_logs), - "note_drafts": _note_draft_rows(note_drafts), - "note_versions": _note_version_rows(note_versions), - "rule_versions": _rule_version_rows(rule_versions), - "settings": _setting_rows(settings), - "rulebooks": _rulebook_rows(rulebooks), - "rulebook_topics": _topic_rows(topics), - "rules": _rule_rows(rules), - "canonical_systems": _canonical_system_rows(canonical_systems), - "rule_systems": _rule_system_rows(rule_system_rows), - "rule_moments": _rule_moment_rows(rule_moment_rows), - "rule_triggers": _rule_trigger_rows(rule_trigger_rows), - "rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments), - "rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments), - "rule_relations": _rule_relation_rows(rule_relations), - "lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links), - "lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule), - "lesson_situations": _lesson_situation_rows(lesson_situations), - "systems": _system_rows( - systems, {c.id: c.slug for c in canonical_systems} - ), - "record_systems": _record_system_rows(record_systems), - "design_systems": _design_system_rows(design_systems), - "design_tokens": _design_token_rows(design_tokens), - "note_usage_events": _usage_event_rows(usage_events), - "rule_usage_events": _rule_usage_event_rows(rule_usage_events), - "system_usage_events": _system_usage_event_rows(system_usage_events), - "retrieval_tuning_events": _retrieval_tuning_event_rows( - retrieval_tuning_events - ), - "moment_mappings": _moment_mapping_rows(moment_mappings), - "repo_bindings": _repo_binding_rows(repo_bindings), - "note_supersessions": _note_supersession_rows(supersessions), - "code_shapes": _code_shape_rows(code_shapes), - "code_shape_events": _code_shape_event_rows(code_shape_events), - "code_shape_uses": _code_shape_use_rows(code_shape_uses), - "code_shape_guard_reviews": _code_shape_guard_review_rows(code_shape_guard_reviews), - **_family_sections( + out.update(_family_sections( platforms, project_platforms, family_ideas, family_idea_platforms, family_idea_references, family_adoptions, family_decisions, - ), - } + )) + return out def _family_sections( diff --git a/src/grimoire/services/backup_file.py b/src/grimoire/services/backup_file.py index 6ed13410..c14b7883 100644 --- a/src/grimoire/services/backup_file.py +++ b/src/grimoire/services/backup_file.py @@ -34,6 +34,7 @@ import io import json import os import tarfile +import tempfile from datetime import datetime, timezone from pathlib import Path from typing import IO @@ -45,6 +46,13 @@ SECTION_SUFFIX = ".jsonl" NAME_PREFIX = "grimoire-" NAME_SUFFIX = ".tar" +# Each section is encoded into a spool file before it goes into the tar, +# because a tar member's header carries its size and so must be written before +# its bytes. A spool past this size moves to a temporary file on disk: the +# largest sections run to tens of megabytes, and the app keeps the memory of +# its largest moment, so a section never sits in memory whole. +SPOOL_IN_MEMORY_BYTES = 1 << 20 + # Grimoire was called Scribe, and archives it wrote carry that name in their # manifest and file name. They are read and counted like any other, so a # backup taken before the rename still restores. @@ -86,14 +94,14 @@ def _split(payload: dict) -> tuple[dict, dict[str, list]]: return header, sections -def _member(name: str, data: bytes) -> tuple[tarfile.TarInfo, io.BytesIO]: +def _member_info(name: str, size: int) -> tarfile.TarInfo: info = tarfile.TarInfo(name) - info.size = len(data) + info.size = size info.mtime = 0 info.mode = 0o644 info.uid = info.gid = 0 info.uname = info.gname = "" - return info, io.BytesIO(data) + return info def write_archive_to(payload: dict, out: IO[bytes], *, app_version: str) -> dict: @@ -111,16 +119,17 @@ def write_archive_to(payload: dict, out: IO[bytes], *, app_version: str) -> dict "header": header, "sections": {name: len(sections[name]) for name in names}, } + head = (json.dumps(manifest, sort_keys=True, indent=2, default=str) + "\n").encode() with tarfile.open(fileobj=out, mode="w", format=tarfile.USTAR_FORMAT) as tar: - tar.addfile(*_member( - MANIFEST_NAME, (json.dumps(manifest, sort_keys=True, indent=2, - default=str) + "\n").encode(), - )) + tar.addfile(_member_info(MANIFEST_NAME, len(head)), io.BytesIO(head)) for name in names: - data = b"".join( - _encode(row).encode() + b"\n" for row in sections[name] - ) - tar.addfile(*_member(name + SECTION_SUFFIX, data)) + with tempfile.SpooledTemporaryFile(max_size=SPOOL_IN_MEMORY_BYTES) as spool: + for row in sections[name]: + spool.write(_encode(row).encode()) + spool.write(b"\n") + size = spool.tell() + spool.seek(0) + tar.addfile(_member_info(name + SECTION_SUFFIX, size), spool) return manifest diff --git a/tests/test_services_backup_file.py b/tests/test_services_backup_file.py index 8e098f1d..8eebf20c 100644 --- a/tests/test_services_backup_file.py +++ b/tests/test_services_backup_file.py @@ -8,6 +8,7 @@ shape this file replaced. """ import io import tarfile +import tracemalloc from datetime import datetime, timezone from unittest.mock import patch @@ -162,6 +163,24 @@ def test_a_failed_write_leaves_nothing_behind(tmp_path): assert list(tmp_path.iterdir()) == [] +def test_a_large_section_is_never_held_in_memory_whole(tmp_path): + """The app keeps the memory of its largest moment, so writing a section + must not build its bytes in memory: the peak while writing stays a small + fraction of the section's size.""" + body = "x" * 1000 + payload = _payload(notes=[{"id": n, "body": body} for n in range(20_000)]) + tracemalloc.start() + try: + with open(tmp_path / "out.tar", "wb") as f: + write_archive_to(payload, f, app_version="v") + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + written = (tmp_path / "out.tar").stat().st_size + assert written > 20_000_000 + assert peak < written // 5, f"peak {peak} bytes while writing {written}" + + def _rewrite(members: dict[str, bytes]) -> io.BytesIO: buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w", format=tarfile.USTAR_FORMAT) as tar: