fix(8822): the backup converts each table as it reads it and streams each section to disk
CI & Build / TypeScript typecheck (push) Successful in 10s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / Python tests (push) Successful in 1m54s
CI & Build / integration (push) Successful in 1m57s
CI & Build / Build & push image (push) Successful in 28s

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 <noreply@anthropic.com>
This commit is contained in:
2026-12-06 10:50:23 -05:00
co-authored by Claude Opus 5.5
parent 6052a66aca
commit f19ba0c798
3 changed files with 169 additions and 134 deletions
+130 -123
View File
@@ -1083,93 +1083,152 @@ async def export_full_backup() -> dict:
""" """
from grimoire.services.instance import get_instance_id 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 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) instance_id = await get_instance_id(session)
users =(await session.execute(select(User).order_by(User.id))).scalars().all() out = {
projects = (await session.execute(select(Project).order_by(Project.id))).scalars().all() "version": BACKUP_VERSION,
milestones = (await session.execute(select(Milestone).order_by(Milestone.id))).scalars().all() "scope": "full",
notes = (await session.execute(select(Note).order_by(Note.id))).scalars().all() "instance_id": instance_id,
task_logs = (await session.execute(select(TaskLog).order_by(TaskLog.id))).scalars().all() "exported_at": datetime.now(timezone.utc).isoformat(),
note_drafts = (await session.execute(select(NoteDraft).order_by(NoteDraft.id))).scalars().all() "_security_notice": (
note_versions = (await session.execute( "This backup contains hashed passwords. "
select(NoteVersion).order_by(NoteVersion.note_id, NoteVersion.id) "Store it securely and restrict access."
)).scalars().all() ),
rule_versions = (await session.execute( "_not_included": _NOT_INCLUDED,
select(RuleVersion).order_by(RuleVersion.rule_id, RuleVersion.id) }
)).scalars().all() out["users"] = await rows(select(User).order_by(User.id), _user_rows)
settings = (await session.execute(select(Setting).order_by(Setting.user_id, Setting.key))).scalars().all() out["projects"] = await rows(select(Project).order_by(Project.id), _project_rows)
systems = (await session.execute(select(System).order_by(System.id))).scalars().all() 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( canonical_systems = (await session.execute(
select(CanonicalSystem).where(CanonicalSystem.deleted_at.is_(None)) select(CanonicalSystem).where(CanonicalSystem.deleted_at.is_(None))
.order_by(CanonicalSystem.order_index, CanonicalSystem.id) .order_by(CanonicalSystem.order_index, CanonicalSystem.id)
)).scalars().all() )).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) select(rule_systems_t.c.rule_id, CanonicalSystem.slug)
.join(CanonicalSystem, CanonicalSystem.id == rule_systems_t.c.canonical_id) .join(CanonicalSystem, CanonicalSystem.id == rule_systems_t.c.canonical_id)
.order_by(rule_systems_t.c.rule_id, CanonicalSystem.slug) .order_by(rule_systems_t.c.rule_id, CanonicalSystem.slug),
)).all() _rule_system_rows,
rule_moment_rows = (await session.execute( )
out["rule_moments"] = await tuples(
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment) 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) .order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment),
)).all() _rule_moment_rows,
rule_trigger_rows = (await session.execute( )
out["rule_triggers"] = await tuples(
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind, select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment) rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
.order_by(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind, .order_by(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment) rule_triggers_t.c.pattern, rule_triggers_t.c.moment),
)).all() _rule_trigger_rows,
rule_moment_judgments = (await session.execute( )
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id) out["rule_moment_judgments"] = await rows(
)).scalars().all() select(RuleMomentJudgment).order_by(RuleMomentJudgment.id),
rule_field_judgments = (await session.execute( _rule_moment_judgment_rows,
select(RuleFieldJudgment).order_by(RuleFieldJudgment.id) )
)).scalars().all() out["rule_field_judgments"] = await rows(
rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all() select(RuleFieldJudgment).order_by(RuleFieldJudgment.id),
lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all() _rule_field_judgment_rows,
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() out["rule_relations"] = await rows(
record_systems = (await session.execute(select(RecordSystem).order_by(RecordSystem.id))).scalars().all() select(RuleRelation).order_by(RuleRelation.id), _rule_relation_rows,
supersessions = ( )
await session.execute(select(NoteSupersession).order_by(NoteSupersession.id)) out["lesson_rule_links"] = await rows(
).scalars().all() 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 # 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 # than needing a second pass — the self-FK is the only ordering
# constraint in this payload. # constraint in this payload.
design_systems = (await session.execute( out["design_systems"] = await rows(
select(DesignSystem).order_by(DesignSystem.parent_id.nullsfirst(), select(DesignSystem).order_by(DesignSystem.parent_id.nullsfirst(),
DesignSystem.id) DesignSystem.id),
)).scalars().all() _design_system_rows,
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() out["design_tokens"] = await rows(
rule_usage_events = ( select(DesignToken).order_by(DesignToken.id), _design_token_rows,
await session.execute(select(RuleUsageEvent).order_by(RuleUsageEvent.id)) )
).scalars().all() out["note_usage_events"] = await rows(
system_usage_events = ( select(NoteUsageEvent).order_by(NoteUsageEvent.id), _usage_event_rows,
await session.execute(select(SystemUsageEvent).order_by(SystemUsageEvent.id)) )
).scalars().all() 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 # Oldest first, so a restored history reads in the order the dials
# actually moved — the sequence IS the argument when a surface has been # actually moved — the sequence IS the argument when a surface has been
# walked up and down. # walked up and down.
retrieval_tuning_events = (await session.execute( out["retrieval_tuning_events"] = await rows(
select(RetrievalTuningEvent).order_by(RetrievalTuningEvent.id) select(RetrievalTuningEvent).order_by(RetrievalTuningEvent.id),
)).scalars().all() _retrieval_tuning_event_rows,
moment_mappings = (await session.execute( )
select(MomentMapping).order_by(MomentMapping.id) out["moment_mappings"] = await rows(
)).scalars().all() select(MomentMapping).order_by(MomentMapping.id), _moment_mapping_rows,
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() out["repo_bindings"] = await rows(
code_shape_events = (await session.execute( select(RepoBinding).order_by(RepoBinding.id), _repo_binding_rows,
select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id) )
)).scalars().all() out["note_supersessions"] = await rows(
code_shape_guard_reviews = (await session.execute( select(NoteSupersession).order_by(NoteSupersession.id),
select(CodeShapeGuardReview).order_by(CodeShapeGuardReview.id) _note_supersession_rows,
)).scalars().all() )
code_shape_uses = (await session.execute( out["code_shapes"] = await rows(select(CodeShape).order_by(CodeShape.id), _code_shape_rows)
select(CodeShapeUse).order_by(CodeShapeUse.shape_id, CodeShapeUse.snippet_id, CodeShapeUse.id) out["code_shape_events"] = await rows(
)).scalars().all() select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id),
rulebooks = (await session.execute(select(Rulebook).order_by(Rulebook.id))).scalars().all() _code_shape_event_rows,
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["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( platforms = (await session.execute(
select(Platform).where(Platform.deleted_at.is_(None)) select(Platform).where(Platform.deleted_at.is_(None))
.order_by(Platform.order_index, Platform.id) .order_by(Platform.order_index, Platform.id)
@@ -1191,63 +1250,11 @@ async def export_full_backup() -> dict:
family_decisions = (await session.execute( family_decisions = (await session.execute(
select(FamilyDecision).order_by(FamilyDecision.id) select(FamilyDecision).order_by(FamilyDecision.id)
)).scalars().all() )).scalars().all()
out.update(_family_sections(
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(
platforms, project_platforms, family_ideas, family_idea_platforms, platforms, project_platforms, family_ideas, family_idea_platforms,
family_idea_references, family_adoptions, family_decisions, family_idea_references, family_adoptions, family_decisions,
), ))
} return out
def _family_sections( def _family_sections(
+20 -11
View File
@@ -34,6 +34,7 @@ import io
import json import json
import os import os
import tarfile import tarfile
import tempfile
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import IO from typing import IO
@@ -45,6 +46,13 @@ SECTION_SUFFIX = ".jsonl"
NAME_PREFIX = "grimoire-" NAME_PREFIX = "grimoire-"
NAME_SUFFIX = ".tar" 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 # 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 # manifest and file name. They are read and counted like any other, so a
# backup taken before the rename still restores. # backup taken before the rename still restores.
@@ -86,14 +94,14 @@ def _split(payload: dict) -> tuple[dict, dict[str, list]]:
return header, sections 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 = tarfile.TarInfo(name)
info.size = len(data) info.size = size
info.mtime = 0 info.mtime = 0
info.mode = 0o644 info.mode = 0o644
info.uid = info.gid = 0 info.uid = info.gid = 0
info.uname = info.gname = "" info.uname = info.gname = ""
return info, io.BytesIO(data) return info
def write_archive_to(payload: dict, out: IO[bytes], *, app_version: str) -> dict: 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, "header": header,
"sections": {name: len(sections[name]) for name in names}, "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: with tarfile.open(fileobj=out, mode="w", format=tarfile.USTAR_FORMAT) as tar:
tar.addfile(*_member( tar.addfile(_member_info(MANIFEST_NAME, len(head)), io.BytesIO(head))
MANIFEST_NAME, (json.dumps(manifest, sort_keys=True, indent=2,
default=str) + "\n").encode(),
))
for name in names: for name in names:
data = b"".join( with tempfile.SpooledTemporaryFile(max_size=SPOOL_IN_MEMORY_BYTES) as spool:
_encode(row).encode() + b"\n" for row in sections[name] for row in sections[name]:
) spool.write(_encode(row).encode())
tar.addfile(*_member(name + SECTION_SUFFIX, data)) spool.write(b"\n")
size = spool.tell()
spool.seek(0)
tar.addfile(_member_info(name + SECTION_SUFFIX, size), spool)
return manifest return manifest
+19
View File
@@ -8,6 +8,7 @@ shape this file replaced.
""" """
import io import io
import tarfile import tarfile
import tracemalloc
from datetime import datetime, timezone from datetime import datetime, timezone
from unittest.mock import patch from unittest.mock import patch
@@ -162,6 +163,24 @@ def test_a_failed_write_leaves_nothing_behind(tmp_path):
assert list(tmp_path.iterdir()) == [] 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: def _rewrite(members: dict[str, bytes]) -> io.BytesIO:
buf = io.BytesIO() buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=tarfile.USTAR_FORMAT) as tar: with tarfile.open(fileobj=buf, mode="w", format=tarfile.USTAR_FORMAT) as tar: