소스 검색

Archives: a slice sent again from the slicer adds a run to its archive (#1634) (#3508)

Keybored 1 주 전
부모
커밋
988f6e757b

+ 0 - 104
.basedpyright/baseline.json

@@ -1627,110 +1627,6 @@
                     "lineCount": 1
                 }
             },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 65,
-                    "endColumn": 67,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 74,
-                    "endColumn": 76,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 38,
-                    "endColumn": 40,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 46,
-                    "endColumn": 56,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 44,
-                    "endColumn": 52,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 46,
-                    "endColumn": 56,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 42,
-                    "endColumn": 48,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 43,
-                    "endColumn": 45,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportArgumentType",
-                "range": {
-                    "startColumn": 35,
-                    "endColumn": 53,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 43,
-                    "endColumn": 53,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 45,
-                    "endColumn": 49,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 39,
-                    "endColumn": 45,
-                    "lineCount": 1
-                }
-            },
-            {
-                "code": "reportOptionalMemberAccess",
-                "range": {
-                    "startColumn": 49,
-                    "endColumn": 62,
-                    "lineCount": 1
-                }
-            },
             {
                 "code": "reportAttributeAccessIssue",
                 "range": {

+ 1 - 0
CHANGELOG.md

@@ -21,6 +21,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **The H2C shows how long each nozzle has printed (#1908, contributed by @Keybored02 in #3507)** — Recent H2C firmware counts the print time of every nozzle, which says more about a nozzle's use than the wear estimate. Hovering over a nozzle on the printer card, in the nozzle rack or on the left and right hotend, now shows its **Print time** next to **Wear**. Firmware that does not report it, and other printers, show no print time. Wiki updated.
 
 ### Changed
+- **A slice sent again from the slicer adds a print to its archive (#1634, requested by @d3nn3s08, contributed by @Keybored02 in #3508)** — A print from the File Manager or the queue already joined the archive of its file, but a print sent from Bambu Studio or OrcaSlicer, or started on the printer, always got a new archive: the slicer writes a new 3MF each time it sends, so the file never matched, and the archive's print count stayed at one. Bambuddy now also keeps the hash of each archive's G-code, and a print whose G-code matches an archive nobody owns, in no project and not from a File Manager file adds a run to that archive. The archive takes the new 3MF in place of its old one and keeps its photos, timelapses, notes, tags and earlier runs; a name set by hand stays, and a name taken from the file follows the new file. While another print of it is running, the archive keeps its file and only gets the run. A model sliced again with other settings gets an archive of its own. OrcaSlicer writes the slicing time into the G-code, so with it only the same slice sent again matches. Archives made before are read once in the background after the update. Wiki updated.
 - **SpoolBuddy writes OpenTag3D 2.004 on NTAG215 and NTAG216 tags (#3500, suggested by @pleasantone)** — SpoolBuddy wrote the first version of the OpenTag3D layout. The current version moved every field, so a reader that only knows it read the brand, colour, weight and temperatures from the wrong places. Tags with room for it now get version 2.004, with material, brand, colour name, up to four colours, minimum and maximum print temperature, net weight and empty spool weight. Version 2 no longer fits on an NTAG213, so those keep the first version. SpoolBuddy picks by the size the tag reports, and falls back to the first version if it can't read it; a SpoolBuddy that hasn't been updated keeps writing the first version. Bambuddy does not track density or bed temperature, so a version 2 tag leaves them unset. Wiki updated.
 - **Profile defaults is compact and has Apply all** — Settings → Filament → Profile defaults showed every default as a large box with all its presets and K profiles, so a few products already filled the page. Each default is now one line (product, colour, slicer preset, and how many printer presets and K profiles it has), sorted by product, with a search box; click a line to see its presets and K profiles. The list scrolls on its own. **Apply all** applies every default to the spools in stock in one go, and like Apply to existing spools it only fills in what a spool doesn't have yet. Wiki updated.
 - **Slicer sidecars on Bambu Studio 02.09.01.70 and OrcaSlicer 2.5.0 (#3442)** — The Bambu Studio sidecar now ships the H3C printer presets (0.2, 0.4, 0.6 and 0.8 mm nozzle). OrcaSlicer has no H3C presets yet. OrcaSlicer 2.5.0 ships its bundled presets in a new packed format, so the sidecar image now fetches the same release's presets as JSON for its preset handling. Slicing with a printer preset saved under a name of its own keeps working on 2.5.0; the sliced file then names the Bambu preset it was saved from as its printer preset. Sidecar images built for older slicer versions work as before.

+ 4 - 0
backend/app/api/routes/library.py

@@ -5344,6 +5344,10 @@ async def slice_and_persist_as_archive(
     from backend.app.services.print_cost_estimate import refresh_plate_estimates
 
     refresh_plate_estimates(new_archive)
+    # Its G-code, so a print of this slice sent from the slicer joins it (#1634)
+    from backend.app.services.archive_gcode_hash import refresh_gcode_hash_async
+
+    await refresh_gcode_hash_async(new_archive)
     db.add(new_archive)
     await db.commit()
     await db.refresh(new_archive)

+ 7 - 0
backend/app/core/database.py

@@ -6107,6 +6107,13 @@ async def _run_migrations(conn):
     # (``print_cost_estimate.fill_plate_estimates``).
     await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN plate_estimates JSON")
 
+    # Migration: the G-code fingerprint of the archive's file (#1634), so a
+    # slice sent again from the slicer adds a run to its archive. Nullable, no
+    # default; filled from the archived file after startup
+    # (``archive_gcode_hash.fill_gcode_hashes``).
+    await _safe_execute(conn, "ALTER TABLE print_archives ADD COLUMN gcode_hash VARCHAR(64)")
+    await _safe_execute(conn, "CREATE INDEX IF NOT EXISTS ix_print_archives_gcode_hash ON print_archives (gcode_hash)")
+
     # Migration: who assigned a spool to a slot, whose cloud sign-in the replay
     # on insert resolves a custom preset with (#3519). Nullable, no backfill:
     # earlier assignments replay as before.

+ 384 - 180
backend/app/main.py

@@ -1693,6 +1693,23 @@ async def _fill_plate_estimates() -> None:
         logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
 
 
+_gcode_hashes_task: asyncio.Task | None = None
+
+
+async def _fill_gcode_hashes() -> None:
+    from backend.app.services.archive_gcode_hash import fill_gcode_hashes
+
+    try:
+        filled = await fill_gcode_hashes(async_session)
+    except asyncio.CancelledError:
+        raise
+    except Exception as exc:
+        logging.getLogger(__name__).warning("[ARCHIVE] Reading G-code fingerprints failed: %s", exc)
+        return
+    if filled:
+        logging.getLogger(__name__).info("[ARCHIVE] Read the G-code fingerprints of %d archive(s)", filled)
+
+
 def _partial_progress_scale(progress: int | float | None) -> float:
     """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
 
@@ -5000,6 +5017,277 @@ async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, sub
     )
 
 
+async def _adopt_archive_for_run(
+    db: AsyncSession,
+    archive,
+    printer_id: int,
+    *,
+    starting_plate_id: int | None,
+    effective_subtask_id: str | None,
+    logger: logging.Logger,
+    started_at: datetime | None = None,
+) -> bool:
+    """Start a print's run on an archive that already exists: a reprint, a
+    queue print of a file printed before, or the same slice sent again from the
+    slicer (#1634). The archive says "printing" from now, without the previous
+    run's outcome, answer or timelapse, and on this printer with this print's
+    job id. False when the printer was deleted meanwhile: the adoption is
+    undone or was refused, the printer is forgotten, and the caller stops.
+    """
+    from backend.app.models.archive import PrintArchive
+
+    # As it was before this adoption: put back if the printer turns
+    # out to have been deleted while it was adopted (below).
+    before_adoption = {
+        attr.columns[0].name: getattr(archive, attr.key)
+        for attr in sa_inspect(PrintArchive).column_attrs
+        if attr.key != "id"
+    }
+
+    # Update archive status to printing
+    archive.status = "printing"
+    archive.started_at = started_at or datetime.now(timezone.utc)
+    # The previous run's outcome is not this one's: a reprint that
+    # completes must not keep showing why the last one failed.
+    archive.failure_reason = None
+    archive.completed_at = None
+
+    # The previous run's answer is still on this row and the
+    # completion prompt is gated on ``user_verdict is None`` (#1898),
+    # so without a reset the second run inherits the first run's
+    # verdict: no prompt at all, and a green "good" badge on a run
+    # nobody ever judged.
+    if archive.confirm_requested:
+        archive.user_verdict = None
+        archive.user_verdict_source = None
+        archive.user_verdict_at = None
+        archive.confirm_token = None
+        archive.confirm_token_used_at = None
+
+    # Reprint of an archive reuses the source row. Without resetting
+    # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
+    # ("already has timelapse") and _capture_finish_photo_from_timelapse
+    # extracts the *original* print's last frame, which then ships in
+    # the completion notification (#1707). Clear the path so the
+    # scanner runs fresh; also unlink the old video file so reprints
+    # don't accumulate orphans in the archive directory. Photos list
+    # is left alone — accumulating one finish photo per run is fine.
+    # The print-start baseline (#2704) is stale for the same reason:
+    # it describes the printer before the previous run. The capture
+    # below overwrites it, but clear it here too so an early failure
+    # can't leave the scan diffing against the wrong snapshot.
+    #
+    # Unlinked only when it is the same plate printing again. Every
+    # plate of a Send All shares this archive, and the video on it
+    # can be the only copy of another plate's run -- the printer's
+    # was deleted once it attached (#3275). That one is left in the
+    # archive directory, which goes with the archive. A video whose
+    # plate is not on record (attached by hand, or before the
+    # column existed) is kept too where the 3MF has other plates,
+    # or cannot be read: nothing tells it apart from another plate's,
+    # and keeping costs one file where deleting can cost the only
+    # copy. On an archive with exactly one plate it is that plate's.
+    archive.timelapse_baseline = None
+    stale_timelapse_relpath = archive.timelapse_path
+    stale_timelapse_plate_id = archive.timelapse_plate_id
+    if stale_timelapse_relpath:
+        archive.timelapse_path = None
+        archive.timelapse_plate_id = None
+    stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
+    if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
+        from backend.app.services.archive import plate_indexes_in_3mf
+
+        plates = await asyncio.to_thread(
+            plate_indexes_in_3mf,
+            app_settings.base_dir / archive.file_path,  # SEC-PATH-OK: stored relative archive path
+        )
+        stale_is_this_plates = len(plates) == 1
+    if stale_timelapse_relpath and not stale_is_this_plates:
+        logger.info(
+            "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
+            stale_timelapse_relpath,
+            stale_timelapse_plate_id,
+            archive.id,
+            starting_plate_id,
+        )
+    # The video is deleted once the adoption stands (below).
+    delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
+    # Update on first-set OR on reprint (the queue dispatcher mints
+    # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
+    # the rewrite for reprints leaves the archive holding the FIRST
+    # run's id; if MQTT then reconnects mid-print, the reconciler
+    # (#1542) compares the stale stored id against the printer's
+    # live id, sees a mismatch, and synthesises a bogus PRINT
+    # COMPLETE — exactly the false-positive "Print Stopped" reported
+    # in #1807. Inequality check preserves the noop-on-stable-push
+    # behaviour the earlier `not archive.subtask_id` guard provided.
+    if effective_subtask_id and archive.subtask_id != effective_subtask_id:
+        archive.subtask_id = effective_subtask_id
+    # #1403 follow-up: VP-queue archives are created with
+    # printer_id=None at queue-add time (we don't know which
+    # printer will run the job yet). When the print actually
+    # starts on a specific printer the expected-archive lookup
+    # used to skip this assignment, leaving printer_id=None
+    # forever — which then disables the "Scan for timelapse"
+    # button in ArchivesPage (gated on !archive.printer_id).
+    if archive.printer_id != printer_id:
+        archive.printer_id = printer_id
+    adopting_id = archive.id  # a rollback expires the object
+    try:
+        await db.commit()
+    except (IntegrityError, StaleDataError):
+        # The archive stays unchanged, or is gone: "delete archives"
+        # removed the row under the adoption, which then matched no
+        # row (StaleDataError) rather than being refused.
+        if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
+            return False
+        raise
+
+    # The printer can be deleted between the check above and this
+    # commit (the route's transaction lasts seconds), and the commit
+    # then adopted the archive anyway: status, verdict and timelapse
+    # changed, and the deleted printer's id written on a row the
+    # route had detached or never touched. Undo the adoption.
+    if await _printer_gone(db, printer_id):
+        logger.info(
+            "Printer %s was deleted while archive %s was adopted; undoing the adoption",
+            printer_id,
+            archive.id,
+        )
+        # Everything as before this adoption. The printer it had
+        # then stays, unless it was the deleted one: the route
+        # detached that row (kept) or deleted it (no row matches).
+        previous_printer = before_adoption["printer_id"]
+        await db.execute(
+            update(PrintArchive)
+            .where(PrintArchive.id == archive.id)
+            .values(
+                {
+                    **before_adoption,
+                    "printer_id": None if previous_printer == printer_id else previous_printer,
+                }
+            )
+        )
+        await db.commit()
+        await forget_printer(printer_id)
+        return False
+
+    await _drop_replaced_plate_videos(
+        db,
+        archive.id,
+        starting_plate_id,
+        stale_timelapse_relpath if delete_stale_video else None,
+        logger,
+    )
+    return True
+
+
+async def _claim_slicer_resend_archive(db: AsyncSession, printer_id: int, source: Path):
+    """The archive a print sent from the slicer adds its run to, or None for a
+    new one (#1634): the same G-code, so the same slice sent again in a new 3MF.
+
+    As a queue print of a file printed before (``_claim_reusable_archive`` in
+    the scheduler): the same owner (who started the print, nobody for a print
+    from the slicer) and no project, and no File Manager file, whose own prints
+    find its archive by the file's bytes. Not one a merge is moving. Held in
+    ``archive_work`` from here, with no await between, until the caller
+    releases it once the run is open.
+
+    Returns the archive and whether something else holds it already: a queue
+    dispatch uploading or printing its file, which the file must stay for.
+    """
+    from backend.app.models.archive import PrintArchive
+    from backend.app.services import archive_work
+    from backend.app.services.archive_gcode_hash import gcode_fingerprint
+
+    # Unzipping a large 3MF takes seconds: off the event loop.
+    fingerprint = await asyncio.to_thread(gcode_fingerprint, source)
+    if not fingerprint:
+        return None
+    owner_id = await _print_user_id_if_still_there(db, printer_manager.get_current_print_user(printer_id))
+    owner = PrintArchive.created_by_id.is_(None) if owner_id is None else PrintArchive.created_by_id == owner_id
+    candidates = (
+        await db.scalars(
+            select(PrintArchive)
+            .where(
+                PrintArchive.gcode_hash == fingerprint,
+                owner,
+                PrintArchive.project_id.is_(None),
+                PrintArchive.library_file_id.is_(None),
+                PrintArchive.deleted_at.is_(None),
+            )
+            .order_by(PrintArchive.id.desc())
+        )
+    ).all()
+    for candidate in candidates:
+        if archive_work.is_merging(candidate.id):
+            continue
+        in_use = archive_work.is_held(candidate.id)
+        archive_work.hold(candidate.id)
+        return candidate, in_use
+    return None
+
+
+async def _start_slicer_resend_run(
+    db: AsyncSession,
+    archive,
+    printer_id: int,
+    *,
+    source: Path,
+    print_data: dict,
+    subtask_id: str | None,
+    started_at: datetime | None,
+    original_filename: str | None,
+    logger: logging.Logger,
+    file_in_use: bool = False,
+):
+    """Start this print's run on the archive ``_claim_slicer_resend_archive``
+    found (#1634). The archive takes the new file in place of its own, unless
+    another print of it is running, or a queue dispatch holds it
+    (``file_in_use``): that one still reads the file (its upload, pauses,
+    objects and estimate), and the G-code is the same. None when the printer
+    was deleted meanwhile; the caller stops.
+    """
+    from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
+
+    printing_elsewhere = file_in_use or (
+        await db.scalar(
+            select(PrintLogEntry.id)
+            .where(PrintLogEntry.archive_id == archive.id, PrintLogEntry.status == RUN_OPEN)
+            .limit(1)
+            .execution_options(**{INCLUDE_OPEN_RUNS: True})
+        )
+        is not None
+    )
+    if not printing_elsewhere:
+        replaced = await ArchiveService(db).archive_print(
+            printer_id=printer_id,
+            source_file=source,
+            print_data=print_data,
+            subtask_id=subtask_id,
+            original_filename=original_filename,
+            replace_archive_id=archive.id,
+        )
+        if replaced is not None:
+            archive = replaced
+        else:
+            # The copy failed its check, or the printer is gone (the adoption
+            # below says so): the run still joins, on the file it has.
+            logger.warning("Archive %s keeps its file: the one sent again could not be taken", archive.id)
+    client = printer_manager.get_client(printer_id)
+    if not await _adopt_archive_for_run(
+        db,
+        archive,
+        printer_id,
+        starting_plate_id=resolve_plate_id(client.state) if client else None,
+        effective_subtask_id=subtask_id,
+        logger=logger,
+        started_at=started_at,
+    ):
+        return None
+    return archive
+
+
 async def on_print_start(printer_id: int, data: dict):
     """Handle print start - archive the 3MF file immediately."""
     logger = logging.getLogger(__name__)
@@ -5395,83 +5683,6 @@ async def on_print_start(printer_id: int, data: dict):
                 return
 
             if archive:
-                # As it was before this adoption: put back if the printer turns
-                # out to have been deleted while it was adopted (below).
-                before_adoption = {
-                    attr.columns[0].name: getattr(archive, attr.key)
-                    for attr in sa_inspect(PrintArchive).column_attrs
-                    if attr.key != "id"
-                }
-
-                # Update archive status to printing
-                archive.status = "printing"
-                archive.started_at = datetime.now(timezone.utc)
-                # The previous run's outcome is not this one's: a reprint that
-                # completes must not keep showing why the last one failed.
-                archive.failure_reason = None
-                archive.completed_at = None
-
-                # The previous run's answer is still on this row and the
-                # completion prompt is gated on ``user_verdict is None`` (#1898),
-                # so without a reset the second run inherits the first run's
-                # verdict: no prompt at all, and a green "good" badge on a run
-                # nobody ever judged.
-                if archive.confirm_requested:
-                    archive.user_verdict = None
-                    archive.user_verdict_source = None
-                    archive.user_verdict_at = None
-                    archive.confirm_token = None
-                    archive.confirm_token_used_at = None
-
-                # Reprint of an archive reuses the source row. Without resetting
-                # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
-                # ("already has timelapse") and _capture_finish_photo_from_timelapse
-                # extracts the *original* print's last frame, which then ships in
-                # the completion notification (#1707). Clear the path so the
-                # scanner runs fresh; also unlink the old video file so reprints
-                # don't accumulate orphans in the archive directory. Photos list
-                # is left alone — accumulating one finish photo per run is fine.
-                # The print-start baseline (#2704) is stale for the same reason:
-                # it describes the printer before the previous run. The capture
-                # below overwrites it, but clear it here too so an early failure
-                # can't leave the scan diffing against the wrong snapshot.
-                #
-                # Unlinked only when it is the same plate printing again. Every
-                # plate of a Send All shares this archive, and the video on it
-                # can be the only copy of another plate's run -- the printer's
-                # was deleted once it attached (#3275). That one is left in the
-                # archive directory, which goes with the archive. A video whose
-                # plate is not on record (attached by hand, or before the
-                # column existed) is kept too where the 3MF has other plates,
-                # or cannot be read: nothing tells it apart from another plate's,
-                # and keeping costs one file where deleting can cost the only
-                # copy. On an archive with exactly one plate it is that plate's.
-                archive.timelapse_baseline = None
-                stale_timelapse_relpath = archive.timelapse_path
-                stale_timelapse_plate_id = archive.timelapse_plate_id
-                starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
-                if stale_timelapse_relpath:
-                    archive.timelapse_path = None
-                    archive.timelapse_plate_id = None
-                stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
-                if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
-                    from backend.app.services.archive import plate_indexes_in_3mf
-
-                    plates = await asyncio.to_thread(
-                        plate_indexes_in_3mf,
-                        app_settings.base_dir / archive.file_path,  # SEC-PATH-OK: stored relative archive path
-                    )
-                    stale_is_this_plates = len(plates) == 1
-                if stale_timelapse_relpath and not stale_is_this_plates:
-                    logger.info(
-                        "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
-                        stale_timelapse_relpath,
-                        stale_timelapse_plate_id,
-                        expected_archive_id,
-                        starting_plate_id,
-                    )
-                # The video is deleted once the adoption stands (below).
-                delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
                 # Persist a restart-stable id so a later restart resumes this
                 # archive by subtask_id instead of name-matching + duplicating
                 # it (#1485). The printer often hasn't echoed subtask_id back
@@ -5487,73 +5698,16 @@ async def on_print_start(printer_id: int, data: dict):
                     _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
                     if _dispatched:
                         effective_subtask_id = str(_dispatched).strip() or None
-                # Update on first-set OR on reprint (the queue dispatcher mints
-                # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
-                # the rewrite for reprints leaves the archive holding the FIRST
-                # run's id; if MQTT then reconnects mid-print, the reconciler
-                # (#1542) compares the stale stored id against the printer's
-                # live id, sees a mismatch, and synthesises a bogus PRINT
-                # COMPLETE — exactly the false-positive "Print Stopped" reported
-                # in #1807. Inequality check preserves the noop-on-stable-push
-                # behaviour the earlier `not archive.subtask_id` guard provided.
-                if effective_subtask_id and archive.subtask_id != effective_subtask_id:
-                    archive.subtask_id = effective_subtask_id
-                # #1403 follow-up: VP-queue archives are created with
-                # printer_id=None at queue-add time (we don't know which
-                # printer will run the job yet). When the print actually
-                # starts on a specific printer the expected-archive lookup
-                # used to skip this assignment, leaving printer_id=None
-                # forever — which then disables the "Scan for timelapse"
-                # button in ArchivesPage (gated on !archive.printer_id).
-                if archive.printer_id != printer_id:
-                    archive.printer_id = printer_id
-                adopting_id = archive.id  # a rollback expires the object
-                try:
-                    await db.commit()
-                except (IntegrityError, StaleDataError):
-                    # The archive stays unchanged, or is gone: "delete archives"
-                    # removed the row under the adoption, which then matched no
-                    # row (StaleDataError) rather than being refused.
-                    if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
-                        return
-                    raise
-
-                # The printer can be deleted between the check above and this
-                # commit (the route's transaction lasts seconds), and the commit
-                # then adopted the archive anyway: status, verdict and timelapse
-                # changed, and the deleted printer's id written on a row the
-                # route had detached or never touched. Undo the adoption.
-                if await _printer_gone(db, printer_id):
-                    logger.info(
-                        "Printer %s was deleted while archive %s was adopted; undoing the adoption",
-                        printer_id,
-                        archive.id,
-                    )
-                    # Everything as before this adoption. The printer it had
-                    # then stays, unless it was the deleted one: the route
-                    # detached that row (kept) or deleted it (no row matches).
-                    previous_printer = before_adoption["printer_id"]
-                    await db.execute(
-                        update(PrintArchive)
-                        .where(PrintArchive.id == archive.id)
-                        .values(
-                            {
-                                **before_adoption,
-                                "printer_id": None if previous_printer == printer_id else previous_printer,
-                            }
-                        )
-                    )
-                    await db.commit()
-                    await forget_printer(printer_id)
-                    return
-
-                await _drop_replaced_plate_videos(
+                starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
+                if not await _adopt_archive_for_run(
                     db,
-                    archive.id,
-                    starting_plate_id,
-                    stale_timelapse_relpath if delete_stale_video else None,
-                    logger,
-                )
+                    archive,
+                    printer_id,
+                    starting_plate_id=starting_plate_id,
+                    effective_subtask_id=effective_subtask_id,
+                    logger=logger,
+                ):
+                    return
 
                 # Track as active print
                 _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
@@ -6588,26 +6742,50 @@ async def on_print_start(printer_id: int, data: dict):
                     await _send_print_start_notification(printer_id, data, logger=logger)
                 return
 
+        # The archive of the same slice sent before, which this print adds a
+        # run to instead of a new archive (#1634). Held until its run is open.
+        joined_archive_id: int | None = None
         try:
             # Archive the file with status "printing"
             service = ArchiveService(db)
+            start_print_data = {
+                **data,
+                "status": "printing",
+                # Where the 3MF came from when the printer had none to
+                # give (#3307), for whoever reads this archive later.
+                **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
+            }
+            # The reused copy's temp name carries the printer id; a
+            # download's is the file's own name, as before.
+            start_filename = downloaded_filename if reused_3mf_from is not None else None
             try:
-                archive = await service.archive_print(
-                    printer_id=printer_id,
-                    source_file=temp_path,
-                    print_data={
-                        **data,
-                        "status": "printing",
-                        # Where the 3MF came from when the printer had none to
-                        # give (#3307), for whoever reads this archive later.
-                        **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
-                    },
-                    subtask_id=subtask_id,
-                    started_at=detected_at,
-                    # The reused copy's temp name carries the printer id; a
-                    # download's is the file's own name, as before.
-                    original_filename=downloaded_filename if reused_3mf_from is not None else None,
-                )
+                claimed = await _claim_slicer_resend_archive(db, printer_id, temp_path)
+                if claimed is not None:
+                    joined, file_in_use = claimed
+                    joined_archive_id = joined.id
+                    archive = await _start_slicer_resend_run(
+                        db,
+                        joined,
+                        printer_id,
+                        source=temp_path,
+                        print_data=start_print_data,
+                        subtask_id=subtask_id,
+                        started_at=detected_at,
+                        original_filename=start_filename,
+                        logger=logger,
+                        file_in_use=file_in_use,
+                    )
+                    if archive is None:
+                        return
+                else:
+                    archive = await service.archive_print(
+                        printer_id=printer_id,
+                        source_file=temp_path,
+                        print_data=start_print_data,
+                        subtask_id=subtask_id,
+                        started_at=detected_at,
+                        original_filename=start_filename,
+                    )
             except IntegrityError:
                 # archive_print removed the folder it had copied the 3MF into.
                 if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
@@ -6643,41 +6821,55 @@ async def on_print_start(printer_id: int, data: dict):
                         logger.warning(
                             "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
                         )
+                    if archive is None:
+                        # Deleted meanwhile: nothing to register the print for.
+                        return
 
-                if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
+                # Not a joined archive: it is not this print's to remove, and
+                # its adoption already checked the printer.
+                if joined_archive_id is None and await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
                     return
 
                 # Track this active print (use both original filename and downloaded filename)
                 _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
                 await _open_run_for(archive_id, printer_id, subtask_id)
 
-                logger.info("Created archive %s for %s", archive.id, downloaded_filename)
+                if joined_archive_id is not None:
+                    logger.info(
+                        "Added the print of %s to archive %s: the same G-code was sent again",
+                        downloaded_filename,
+                        archive_id,
+                    )
+                else:
+                    logger.info("Created archive %s for %s", archive.id, downloaded_filename)
 
                 _maybe_start_layer_timelapse(printer, printer_id, archive.id)
 
                 # Record starting energy from smart plug if available (#941: persisted column)
                 await _record_energy_start(archive, printer_id, db, context="auto-archive")
 
-                await ws_manager.send_archive_created(
-                    {
-                        "id": archive.id,
-                        "printer_id": archive.printer_id,
-                        "filename": archive.filename,
-                        "print_name": archive.print_name,
-                        "status": archive.status,
-                    }
-                )
+                archive_event = {
+                    "id": archive.id,
+                    "printer_id": archive.printer_id,
+                    "filename": archive.filename,
+                    "print_name": archive.print_name,
+                    "status": archive.status,
+                }
+                if joined_archive_id is not None:
+                    await ws_manager.send_archive_updated(archive_event)
+                else:
+                    await ws_manager.send_archive_created(archive_event)
 
-                # MQTT relay - publish archive created
-                try:
-                    await mqtt_relay.on_archive_created(
-                        archive_id=archive.id,
-                        print_name=archive.print_name,
-                        printer_name=printer.name,
-                        status=archive.status,
-                    )
-                except Exception:
-                    pass  # Don't fail if MQTT fails
+                    # MQTT relay - publish archive created
+                    try:
+                        await mqtt_relay.on_archive_created(
+                            archive_id=archive.id,
+                            print_name=archive.print_name or "",
+                            printer_name=printer.name if printer else "",
+                            status=archive.status,
+                        )
+                    except Exception:
+                        pass  # Don't fail if MQTT fails
 
                 # Send notification with archive data (new archive created)
                 if not notification_sent:
@@ -6747,6 +6939,10 @@ async def on_print_start(printer_id: int, data: dict):
                 await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
                 await _forget_if_printer_gone(printer_id)
         finally:
+            if joined_archive_id is not None:
+                from backend.app.services import archive_work
+
+                archive_work.release(joined_archive_id)
             # Keep temp_path around until print completes so the cover endpoint
             # can reuse it (#972). Cache eviction in on_print_complete deletes
             # the file. If the cache entry was evicted early (file vanished),
@@ -12101,6 +12297,12 @@ async def lifespan(app: FastAPI):
     global _plate_estimates_task
     _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
 
+    # The G-code fingerprint of archives made before it was kept (#1634), read
+    # from their files in the background: until then a slice sent again from
+    # the slicer archives anew, as before.
+    global _gcode_hashes_task
+    _gcode_hashes_task = asyncio.create_task(_fill_gcode_hashes())
+
     # Register an app-scoped httpx client for Bambu Cloud services so
     # per-request BambuCloudService instances reuse the same connection pool
     # (important for routes like /cloud/filament-info that chain many
@@ -12592,6 +12794,8 @@ async def lifespan(app: FastAPI):
     stop_auth_cleanup()
     if _plate_estimates_task is not None and not _plate_estimates_task.done():
         _plate_estimates_task.cancel()
+    if _gcode_hashes_task is not None and not _gcode_hashes_task.done():
+        _gcode_hashes_task.cancel()
     from backend.app.services import announcements as announcements_service
 
     announcements_service.stop()

+ 4 - 0
backend/app/models/archive.py

@@ -29,6 +29,10 @@ class PrintArchive(Base):
     file_path: Mapped[str] = mapped_column(String(500))
     file_size: Mapped[int] = mapped_column(Integer)
     content_hash: Mapped[str | None] = mapped_column(String(64))  # SHA256 hash for duplicate detection
+    # SHA256 of the file's G-code only (#1634): a slice sent again from the
+    # slicer, in a new 3MF, adds a run to this archive. "" = read, no G-code;
+    # NULL = not read yet. See services/archive_gcode_hash.
+    gcode_hash: Mapped[str | None] = mapped_column(String(64), index=True)
     thumbnail_path: Mapped[str | None] = mapped_column(String(500))
     timelapse_path: Mapped[str | None] = mapped_column(String(500))
     # The plate whose run produced ``timelapse_path`` (#3275). Every plate of a

+ 146 - 5
backend/app/services/archive.py

@@ -1,3 +1,4 @@
+import asyncio
 import hashlib
 import html
 import json
@@ -1315,6 +1316,7 @@ class ArchiveService:
         slicer_ams_mapping_printer_id: int | None = None,
         update_archive_id: int | None = None,
         started_at: datetime | None = None,
+        replace_archive_id: int | None = None,
     ) -> PrintArchive | None:
         """Archive a 3MF file with metadata.
 
@@ -1365,6 +1367,14 @@ class ArchiveService:
                 better to say about them.
             started_at: When the print started, for a "printing" archive whose 3MF
                 was downloaded after the start (#3327). Defaults to now.
+            replace_archive_id: Put this file in place of an existing archive's: the
+                same slice sent again from the slicer (#1634, same G-code in a new
+                3MF). The file goes into the archive's own folder, where its photos
+                and timelapses are, and the old one is deleted. Everything read from
+                the file is the new one's; what belongs to the archive (owner,
+                project, notes, tags, photos, runs, a saved AMS mapping) stays, and so
+                does a name set by hand. Status and start are the caller's: the run
+                is opened as for any print of an existing archive.
         """
         # Verify printer exists if specified
         if printer_id is not None:
@@ -1382,6 +1392,18 @@ class ArchiveService:
         archive_dir = (
             settings.archive_dir / printer_folder / archive_name
         )  # SEC-PATH-OK: printer_folder = str(int|None) → digits or "unassigned"; archive_name = f"{timestamp}_{display_stem}" where resolve_display_stem strips path components via Path(filename).name
+        # A slicer resend replacing an archive's file (#1634): into that
+        # archive's folder, which holds its photos and timelapses and which
+        # deleting it removes. One without a file (restored from a backup, a
+        # fallback) gets a new folder, as a fallback given its 3MF does.
+        replacing: PrintArchive | None = None
+        if replace_archive_id is not None:
+            replacing = await self.db.get(PrintArchive, replace_archive_id)
+            if replacing is None:
+                logger.warning("archive_print: archive %s to replace the file of no longer exists", replace_archive_id)
+                return None
+            if replacing.file_path:
+                archive_dir = resolve_archive_dir(replacing)
         # Removed again if the row is not written (below); only a folder this
         # call created, never another archive's of the same name.
         created_archive_dir = not archive_dir.exists()
@@ -1391,7 +1413,12 @@ class ArchiveService:
         # short-read quirk that silently truncated 3MF archives on some
         # platforms — see _copy_and_fsync and #1032).
         dest_file = archive_dir / source_file.name
-        _copy_and_fsync(source_file, dest_file)
+        # Over the replaced archive's file of the same name only once the copy
+        # is whole and checked, so a failed copy leaves the archive its file.
+        copy_target = dest_file
+        if replacing is not None and dest_file.exists():
+            copy_target = archive_dir / f".replacing-{source_file.name}"
+        _copy_and_fsync(source_file, copy_target)
 
         # If we just archived a 3MF, verify the dest is a valid ZIP before
         # going any further. Staying quiet here is how #1032 escaped review —
@@ -1400,18 +1427,18 @@ class ArchiveService:
         if (
             source_file.suffix.lower() == ".3mf"
             and zipfile.is_zipfile(source_file)
-            and not zipfile.is_zipfile(dest_file)
+            and not zipfile.is_zipfile(copy_target)
         ):
             try:
                 src_size = source_file.stat().st_size
-                dst_size = dest_file.stat().st_size
+                dst_size = copy_target.stat().st_size
             except OSError:
                 src_size = dst_size = -1
             logger.error(
                 "Archive copy corrupted 3MF: src=%s (%s bytes, valid ZIP) -> dst=%s (%s bytes, NOT a ZIP). Refusing to create archive row.",
                 source_file,
                 src_size,
-                dest_file,
+                copy_target,
                 dst_size,
             )
             # Narrow cleanup: remove only the truncated file and the archive
@@ -1419,7 +1446,7 @@ class ArchiveService:
             # exist_ok=True so it could in theory pre-date this call (e.g.
             # same-second same-filename collision); rmtree would be too broad.
             try:
-                dest_file.unlink()
+                copy_target.unlink()
             except OSError:
                 pass
             try:
@@ -1428,8 +1455,16 @@ class ArchiveService:
                 pass  # directory not empty — leave untouched
             return None
 
+        if copy_target != dest_file:
+            os.replace(copy_target, dest_file)
+
         # Compute content hash for duplicate detection
         content_hash = self.compute_file_hash(dest_file)
+        # And of its G-code alone, so the same slice sent again in a new 3MF
+        # adds a run to this archive (#1634). Off the event loop: it unzips.
+        from backend.app.services.archive_gcode_hash import NO_GCODE, gcode_fingerprint
+
+        gcode_hash = await asyncio.to_thread(gcode_fingerprint, dest_file) or NO_GCODE
 
         # Extract plate number from filename (e.g., "plate_5" from "/data/Metadata/plate_5.gcode")
         plate_number = None
@@ -1503,6 +1538,25 @@ class ArchiveService:
 
         # Recovery of an existing fallback row: assign the freshly-parsed values
         # onto it rather than adding a second archive for the same print (#2957).
+        if replacing is not None:
+            return await self._take_replacement_file(
+                replacing,
+                dest_file=dest_file,
+                filename=original_filename or source_file.name,
+                print_name=(
+                    clean_display_name(display_stem)
+                    if prefer_filename_for_name
+                    else (clean_display_name(metadata.get("print_name")) or clean_display_name(display_stem))
+                ),
+                content_hash=content_hash,
+                gcode_hash=gcode_hash,
+                thumbnail_path=thumbnail_path,
+                metadata=metadata,
+                cost=cost,
+                quantity=quantity,
+                plate_id=plate_id,
+            )
+
         if update_archive_id is not None:
             existing = await self.db.get(PrintArchive, update_archive_id)
             if existing is None:
@@ -1526,6 +1580,7 @@ class ArchiveService:
             existing.file_path = str(dest_file.relative_to(settings.base_dir))
             existing.file_size = dest_file.stat().st_size
             existing.content_hash = content_hash
+            existing.gcode_hash = gcode_hash
             existing.thumbnail_path = thumbnail_path
             existing.print_name = (
                 clean_display_name(display_stem)
@@ -1576,6 +1631,7 @@ class ArchiveService:
             file_path=str(dest_file.relative_to(settings.base_dir)),
             file_size=dest_file.stat().st_size,
             content_hash=content_hash,
+            gcode_hash=gcode_hash,
             thumbnail_path=thumbnail_path,
             # clean_display_name because the 3MF's own metadata reaches this
             # verbatim, and a control character in it renders nowhere and
@@ -1633,6 +1689,91 @@ class ArchiveService:
 
         return archive
 
+    async def _take_replacement_file(
+        self,
+        archive: PrintArchive,
+        *,
+        dest_file: Path,
+        filename: str,
+        print_name: str | None,
+        content_hash: str,
+        gcode_hash: str,
+        thumbnail_path: str | None,
+        metadata: dict,
+        cost: float | None,
+        quantity: int,
+        plate_id: int | None,
+    ) -> PrintArchive:
+        """Give ``archive`` the file just placed at ``dest_file`` in place of its
+        own (``archive_print(replace_archive_id=...)``, #1634), and delete the
+        old one once that is committed."""
+        old_file = (
+            settings.base_dir / archive.file_path if archive.file_path else None
+        )  # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
+        old_extra = archive.extra_data or {}
+
+        # A name the old file gave follows the file; one set by hand stays.
+        # Both ways archive_print names a file: its 3MF title, or its file name.
+        generated = {
+            clean_display_name(old_extra.get("print_name")),
+            clean_display_name(resolve_display_stem(archive.filename)) if archive.filename else None,
+        } - {None}
+        if print_name and (not archive.print_name or archive.print_name in generated):
+            archive.print_name = print_name
+
+        archive.filename = filename
+        archive.file_path = str(dest_file.relative_to(settings.base_dir))
+        archive.file_size = dest_file.stat().st_size
+        archive.content_hash = content_hash
+        archive.gcode_hash = gcode_hash
+        # Earlier runs point at the old thumbnail by path: one of another name
+        # stays in the folder for them, one of the same name now shows the new
+        # file's (the same slice).
+        if thumbnail_path is not None:
+            archive.thumbnail_path = thumbnail_path
+        # The same G-code, so what the new 3MF leaves out the old one said.
+        for field in (
+            "print_time_seconds",
+            "filament_used_grams",
+            "filament_type",
+            "filament_color",
+            "layer_height",
+            "total_layers",
+            "nozzle_diameter",
+            "bed_temperature",
+            "bed_type",
+            "nozzle_temperature",
+            "sliced_for_model",
+            "makerworld_url",
+            "designer",
+        ):
+            value = metadata.get(field)
+            if value is not None:
+                setattr(archive, field, value)
+        if cost is not None:
+            archive.cost = cost
+        archive.quantity = quantity
+        # The new file's description. Of what is not the file's, only the saved
+        # AMS pick is the archive's (a pause warning is its last run's).
+        extra = dict(metadata)
+        if "slicer_ams_mapping" in old_extra:
+            extra["slicer_ams_mapping"] = old_extra["slicer_ams_mapping"]
+        archive.extra_data = extra
+        if plate_id is not None:
+            archive.plate_id = plate_id
+        from backend.app.services.print_cost_estimate import refresh_plate_estimates
+
+        refresh_plate_estimates(archive)
+        await self.db.commit()
+        await self.db.refresh(archive)
+
+        if old_file is not None and old_file != dest_file:
+            try:
+                old_file.unlink(missing_ok=True)
+            except OSError as exc:
+                logger.warning("Could not delete the replaced file %s of archive %s: %s", old_file, archive.id, exc)
+        return archive
+
     async def get_archive(self, archive_id: int) -> PrintArchive | None:
         """Get an archive by ID with relationships loaded."""
         from sqlalchemy.orm import selectinload

+ 134 - 0
backend/app/services/archive_gcode_hash.py

@@ -0,0 +1,134 @@
+"""The G-code fingerprint of an archive's file (#1634).
+
+``content_hash`` is the SHA256 of the archived file's bytes. A slicer that sends
+the same slice again writes a new 3MF around it (zip entry times, metadata), so
+the two files differ in every byte but their G-code. ``gcode_hash`` is the
+SHA256 of the G-code alone: every ``Metadata/plate_N.gcode`` of a 3MF in plate
+order, each with its name and size, or the bytes of a plain ``.gcode`` file.
+
+A print sent from the slicer whose G-code matches an archive adds a run to that
+archive instead of archiving the file again (``main._claim_slicer_resend_archive``).
+A file sliced again with other settings has other G-code and stays separate.
+OrcaSlicer writes the slicing time into the G-code header, so with it only the
+same slice sent again matches, not the same model sliced again.
+
+``NO_GCODE`` ("") marks an archive read without G-code (no file, not a sliced
+file, unreadable), so it is read once; NULL is not read yet. Reading unzips the
+file, which takes seconds for a large 3MF: callers on the event loop go through
+``asyncio.to_thread`` (``refresh_gcode_hash_async``).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import logging
+import re
+import zipfile
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select, update
+
+from backend.app.core.config import settings
+from backend.app.models.archive import PrintArchive
+
+logger = logging.getLogger(__name__)
+
+NO_GCODE = ""
+
+_PLATE_GCODE = re.compile(r"^Metadata/plate_(\d+)\.gcode$")
+_CHUNK = 1 << 20
+
+
+def gcode_fingerprint(path: Path) -> str | None:
+    """SHA256 of the G-code in the file at ``path``, or None when it holds none
+    or cannot be read."""
+    try:
+        if zipfile.is_zipfile(path):
+            with zipfile.ZipFile(path) as zf:
+                plates = sorted(
+                    (int(m.group(1)), info)
+                    for info in zf.infolist()
+                    if (m := _PLATE_GCODE.match(info.filename)) and not info.is_dir()
+                )
+                if not plates:
+                    return None
+                digest = hashlib.sha256()
+                for _number, info in plates:
+                    # Name and length first: two files splitting the same bytes
+                    # over other plates are not one.
+                    digest.update(f"{info.filename}\0{info.file_size}\0".encode())
+                    with zf.open(info) as handle:
+                        for chunk in iter(lambda: handle.read(_CHUNK), b""):
+                            digest.update(chunk)
+                return digest.hexdigest()
+        if path.suffix.lower() == ".gcode":
+            digest = hashlib.sha256()
+            with path.open("rb") as handle:
+                for chunk in iter(lambda: handle.read(_CHUNK), b""):
+                    digest.update(chunk)
+            return digest.hexdigest()
+    except (OSError, zipfile.BadZipFile, zipfile.LargeZipFile, RuntimeError, ValueError) as exc:
+        logger.debug("G-code fingerprint of %s failed: %s", path, exc)
+    return None
+
+
+def read_gcode_hash(archive: Any) -> str | None:
+    """The G-code fingerprint of the archive's file on disk: ``NO_GCODE`` for a
+    file without readable G-code, None when there is no file to read."""
+    if not archive.file_path:
+        return None
+    path = settings.base_dir / archive.file_path  # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
+    if not path.is_file():
+        return None
+    return gcode_fingerprint(path) or NO_GCODE
+
+
+def refresh_gcode_hash(archive: PrintArchive) -> None:
+    """Read the G-code fingerprint of the archive's file into it: when the
+    archive is made, or given a file. Does not commit."""
+    fingerprint = read_gcode_hash(archive)
+    if fingerprint is not None:
+        archive.gcode_hash = fingerprint
+
+
+async def refresh_gcode_hash_async(archive: PrintArchive) -> None:
+    """``refresh_gcode_hash`` with the read off the event loop."""
+    fingerprint = await asyncio.to_thread(read_gcode_hash, archive)
+    if fingerprint is not None:
+        archive.gcode_hash = fingerprint
+
+
+async def fill_gcode_hashes(session_factory, batch: int = 100) -> int:
+    """Give every archive not yet read its G-code fingerprint, from its file.
+    An archive whose file is missing or unreadable gets ``NO_GCODE``: it is
+    read once. Returns how many were read.
+
+    Each is written only while it is still unread: an archive given its file
+    meanwhile (``refresh_gcode_hash``) keeps what that read."""
+    filled = 0
+    last_id = 0
+    while True:
+        async with session_factory() as db:
+            rows = (
+                await db.execute(
+                    select(PrintArchive.id, PrintArchive.file_path)
+                    .where(PrintArchive.gcode_hash.is_(None), PrintArchive.id > last_id)
+                    .order_by(PrintArchive.id)
+                    .limit(batch)
+                )
+            ).all()
+            if not rows:
+                return filled
+            for row in rows:
+                fingerprint = await asyncio.to_thread(read_gcode_hash, row)
+                written = await db.execute(
+                    update(PrintArchive)
+                    .where(PrintArchive.id == row.id, PrintArchive.gcode_hash.is_(None))
+                    .values(gcode_hash=fingerprint if fingerprint is not None else NO_GCODE)
+                    .execution_options(synchronize_session=False)
+                )
+                filled += written.rowcount or 0
+            last_id = rows[-1].id
+            await db.commit()

+ 3 - 0
backend/app/services/archive_merge.py

@@ -42,6 +42,7 @@ from backend.app.models.archive_alias import ArchiveAlias
 from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
 from backend.app.models.print_queue import PrintQueueItem
 from backend.app.services import archive_work
+from backend.app.services.archive_gcode_hash import refresh_gcode_hash_async
 from backend.app.services.print_cost_estimate import refresh_plate_estimates
 from backend.app.utils.archive_paths import archive_dir, archive_photos_dir, find_archive_photo
 from backend.app.utils.local_time import utcnow_naive
@@ -542,6 +543,8 @@ async def _merge(
             # The same file (one hash), but the survivor's was missing: its
             # plates are read from the one it takes over (#3375).
             refresh_plate_estimates(survivor)
+            # And its G-code, which the missing file could not give (#1634).
+            await refresh_gcode_hash_async(survivor)
         for run in runs[archive.id]:
             if run.photos:
                 run.photos = [photos[p] for p in run.photos if p in photos]

+ 1 - 0
backend/app/services/github_backup.py

@@ -901,6 +901,7 @@ class GitHubBackupService:
                 "filename": a.filename,
                 "file_size": a.file_size,
                 "content_hash": a.content_hash,
+                "gcode_hash": a.gcode_hash,
                 "print_name": a.print_name,
                 "print_time_seconds": a.print_time_seconds,
                 "filament_used_grams": a.filament_used_grams,

+ 14 - 0
backend/app/services/github_restore.py

@@ -1686,6 +1686,11 @@ class GitHubRestoreService:
                 file_path="",
                 file_size=entry.get("file_size") or 0,
                 content_hash=entry.get("content_hash"),
+                # The file is not in the backup, so its G-code cannot be read
+                # here: the backup's fingerprint lets a print of the same slice
+                # sent from the slicer join this archive and give it the file
+                # (#1634). Older backups have none, and the fill marks it read.
+                gcode_hash=_gcode_hash_of(entry),
                 **fields,
             )
             created_at = _parse_dt(entry.get("created_at"))
@@ -2740,3 +2745,12 @@ class GitHubRestoreService:
 
 # Singleton instance
 github_restore_service = GitHubRestoreService()
+
+
+_GCODE_HASH = re.compile(r"^[0-9a-f]{64}$")
+
+
+def _gcode_hash_of(entry: dict) -> str | None:
+    """The backed-up G-code fingerprint (#1634), when it is one."""
+    value = entry.get("gcode_hash")
+    return value if isinstance(value, str) and _GCODE_HASH.match(value) else None

+ 20 - 0
backend/tests/integration/test_archive_merge.py

@@ -7,6 +7,7 @@ alias, their money untouched.
 
 from __future__ import annotations
 
+import zipfile
 from datetime import datetime, timedelta
 from pathlib import Path
 from types import SimpleNamespace
@@ -583,6 +584,25 @@ async def test_the_survivor_reads_its_plates_from_the_file_it_takes_over(async_c
     assert archive.plate_estimates == PLATES
 
 
+async def test_the_survivor_reads_the_gcode_of_the_file_it_takes_over(async_client, db_session, files, dupes):
+    """#1634: a slice sent again from the slicer finds the survivor by it."""
+    from backend.app.services.archive_gcode_hash import NO_GCODE, gcode_fingerprint
+
+    (dupes.x_dir / "file.3mf").unlink()
+    for folder in (dupes.y_dir, dupes.z_dir):
+        with zipfile.ZipFile(folder / "file.3mf", "w") as zf:
+            zf.writestr("Metadata/plate_1.gcode", "G28\n")
+    survivor = await db_session.get(PrintArchive, dupes.x)
+    survivor.gcode_hash = NO_GCODE  # read while its file was missing
+    await db_session.commit()
+
+    await async_client.post("/api/v1/archives/merge", json={"survivor_ids": [dupes.x]})
+
+    archive = await _row(db_session, PrintArchive, dupes.x)
+    assert archive.gcode_hash == gcode_fingerprint(files / archive.file_path)
+    assert archive.gcode_hash not in (None, NO_GCODE)
+
+
 async def test_a_copy_that_fails_leaves_no_partial_file(files):
     from backend.app.services.archive_merge import _Files
 

+ 3 - 0
backend/tests/integration/test_external_print_confirmation_1898.py

@@ -141,6 +141,9 @@ async def _drive_print_start(
         pm.get_status = MagicMock(return_value=state)
         pm.get_printer = MagicMock(return_value=MagicMock(serial_number="TEST1898"))
         pm.get_client = MagicMock(return_value=None)  # else its mock dispatch id is stored
+        pm.get_current_print_user = MagicMock(return_value=None)  # a print nobody started in Bambuddy
+        mocks["ws_manager"] = ws
+        mocks["mqtt_relay"] = relay
 
         from backend.app.main import on_print_start
 

+ 245 - 0
backend/tests/integration/test_gcode_hash_paths_1634.py

@@ -0,0 +1,245 @@
+"""The G-code fingerprint every archive keeps (#1634).
+
+A print sent from the slicer joins the archive with the same G-code, so each
+way an archive gets a file reads it: a new archive, a fallback given its 3MF, a
+re-slice, a merge survivor that takes over a file. A restore has no file and
+takes the backup's; archives made before are read once after startup. All of
+them read it off the event loop: unzipping a large 3MF takes seconds.
+"""
+
+from __future__ import annotations
+
+import json
+import zipfile
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+from sqlalchemy import delete, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from backend.app.core.config import settings as app_settings
+from backend.app.models.archive import PrintArchive
+from backend.app.services import archive_gcode_hash
+from backend.app.services.archive_gcode_hash import NO_GCODE, fill_gcode_hashes, gcode_fingerprint
+
+pytestmark = pytest.mark.integration
+
+DIR = "archives/gcode"
+GCODE = b"; HEADER_BLOCK_START\nG28\nG1 X10 Y10 F3000\n"
+
+
+def _three_mf(path, plates: dict[int, bytes] | None = None, *, model: str = "<model/>", when=(2026, 1, 1, 0, 0, 0)):
+    """A sliced 3MF; ``when`` and ``model`` stand for what a new export changes."""
+    path.parent.mkdir(parents=True, exist_ok=True)
+    with zipfile.ZipFile(path, "w") as zf:
+        zf.writestr(zipfile.ZipInfo("3D/3dmodel.model", date_time=when), model)
+        for number, gcode in (plates if plates is not None else {1: GCODE}).items():
+            zf.writestr(zipfile.ZipInfo(f"Metadata/plate_{number}.gcode", date_time=when), gcode)
+    return path
+
+
+@pytest.fixture
+def files(tmp_path, monkeypatch):
+    monkeypatch.setattr(app_settings, "base_dir", tmp_path)
+    monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
+    return tmp_path
+
+
+@pytest.fixture
+def off_the_loop(monkeypatch):
+    """Records what is read through asyncio.to_thread."""
+    import asyncio
+
+    calls: list = []
+    real = asyncio.to_thread
+
+    async def to_thread(fn, *args, **kwargs):
+        calls.append(fn)
+        return await real(fn, *args, **kwargs)
+
+    monkeypatch.setattr(asyncio, "to_thread", to_thread)
+    return calls
+
+
+class TestFingerprint:
+    def test_a_new_export_of_the_same_slice_has_the_same_fingerprint(self, tmp_path):
+        first = _three_mf(tmp_path / "a.3mf")
+        again = _three_mf(tmp_path / "b.3mf", model="<model changed='1'/>", when=(2026, 2, 2, 12, 0, 0))
+
+        assert first.read_bytes() != again.read_bytes()
+        assert gcode_fingerprint(first) == gcode_fingerprint(again)
+
+    def test_another_slice_has_another(self, tmp_path):
+        first = _three_mf(tmp_path / "a.3mf")
+        resliced = _three_mf(tmp_path / "b.3mf", {1: GCODE + b"G1 Z0.2\n"})
+
+        assert gcode_fingerprint(first) != gcode_fingerprint(resliced)
+
+    def test_the_same_gcode_on_another_plate_is_another_file(self, tmp_path):
+        assert gcode_fingerprint(_three_mf(tmp_path / "a.3mf", {1: GCODE})) != gcode_fingerprint(
+            _three_mf(tmp_path / "b.3mf", {2: GCODE})
+        )
+
+    def test_every_plate_counts_in_plate_order(self, tmp_path):
+        both = _three_mf(tmp_path / "a.3mf", {1: GCODE, 2: b"G28\n"})
+        swapped = _three_mf(tmp_path / "b.3mf", {2: b"G28\n", 1: GCODE})
+        one = _three_mf(tmp_path / "c.3mf", {1: GCODE})
+
+        assert gcode_fingerprint(both) == gcode_fingerprint(swapped)
+        assert gcode_fingerprint(both) != gcode_fingerprint(one)
+
+    def test_a_plain_gcode_file_is_its_bytes(self, tmp_path):
+        import hashlib
+
+        path = tmp_path / "cube.gcode"
+        path.write_bytes(GCODE)
+
+        assert gcode_fingerprint(path) == hashlib.sha256(GCODE).hexdigest()
+
+    @pytest.mark.parametrize(
+        "write",
+        [
+            lambda p: _three_mf(p, {}),  # a project, not sliced
+            lambda p: p.write_bytes(b"PK\x03\x04 not really a zip"),
+            lambda p: p.write_bytes(b"solid cube\nendsolid\n"),
+        ],
+    )
+    def test_a_file_without_readable_gcode_has_none(self, tmp_path, write):
+        path = tmp_path / "f.3mf"
+        write(path)
+
+        assert gcode_fingerprint(path) is None
+
+
+class TestNewArchives:
+    async def test_an_archived_print_keeps_its_fingerprint(self, files, db_session, printer_factory, off_the_loop):
+        from backend.app.services.archive import ArchiveService
+
+        printer = await printer_factory()
+        source = _three_mf(files / "upload" / "a.gcode.3mf")
+
+        archive = await ArchiveService(db_session).archive_print(printer.id, source)
+
+        assert archive.gcode_hash == gcode_fingerprint(source)
+        assert gcode_fingerprint in off_the_loop
+
+    async def test_a_file_without_gcode_is_marked_read(self, files, db_session, printer_factory):
+        from backend.app.services.archive import ArchiveService
+
+        printer = await printer_factory()
+        source = _three_mf(files / "upload" / "project.3mf", {})
+
+        archive = await ArchiveService(db_session).archive_print(printer.id, source)
+
+        assert archive.gcode_hash == NO_GCODE
+
+    async def test_a_print_given_its_3mf_later_reads_its_fingerprint(self, files, db_session, printer_factory):
+        from backend.app.services.archive import ArchiveService
+
+        printer = await printer_factory()
+        fallback = PrintArchive(printer_id=printer.id, filename="a.3mf", file_path="", file_size=0, status="printing")
+        db_session.add(fallback)
+        await db_session.commit()
+        source = _three_mf(files / "upload" / "a.gcode.3mf")
+
+        archive = await ArchiveService(db_session).archive_print(printer.id, source, update_archive_id=fallback.id)
+
+        assert (archive.id, archive.gcode_hash) == (fallback.id, gcode_fingerprint(source))
+
+    async def test_a_reslice_reads_its_fingerprint(
+        self, files, db_session, archive_factory, printer_factory, off_the_loop
+    ):
+        from backend.tests.integration.test_slice_archive_output_path_2832 import _slice, _stub_slicer
+
+        printer = await printer_factory()
+        source = await archive_factory(printer.id, print_name="Bracket", filename="Bracket.3mf")
+        sliced = _three_mf(files / "sliced.3mf").read_bytes()
+
+        # _slice stubs the slicer with a file that is not a 3MF: this one is.
+        with patch(
+            "backend.tests.integration.test_slice_archive_output_path_2832._stub_slicer", lambda: _stub_slicer(sliced)
+        ):
+            response = await _slice(db_session, source, "Bracket.3mf")
+
+        archive = await db_session.get(PrintArchive, response.archive_id)
+        assert archive.gcode_hash == gcode_fingerprint(files / "sliced.3mf")
+        assert archive_gcode_hash.read_gcode_hash in off_the_loop
+
+
+class TestBackupAndRestore:
+    async def test_a_restored_archive_keeps_its_fingerprint(self, db_session, printer_factory):
+        """A restore brings back no file to read it from."""
+        from backend.app.schemas.github_backup import RestoreCategory
+        from backend.app.services.github_backup import github_backup_service
+        from backend.app.services.github_restore import GitHubRestoreService
+
+        printer = await printer_factory()
+        db_session.add(
+            PrintArchive(
+                printer_id=printer.id,
+                filename="a.3mf",
+                file_path="archives/t/a.3mf",
+                file_size=1,
+                content_hash="hash-a",
+                gcode_hash="a" * 64,
+                print_name="A",
+                status="completed",
+            )
+        )
+        await db_session.commit()
+        backup: dict = {}
+        await github_backup_service._collect_archives(db_session, backup)
+        backup = json.loads(json.dumps(backup))
+        await db_session.execute(delete(PrintArchive))
+        await db_session.commit()
+
+        await GitHubRestoreService()._apply(db_session, backup, [RestoreCategory.ARCHIVES], False)
+
+        restored = (await db_session.scalars(select(PrintArchive))).one()
+        assert (restored.file_path, restored.gcode_hash) == ("", "a" * 64)
+
+    @pytest.mark.parametrize("value", [None, "", "not-a-hash", 42])
+    def test_a_backup_without_one_restores_none(self, value):
+        from backend.app.services.github_restore import _gcode_hash_of
+
+        assert _gcode_hash_of({"gcode_hash": value} if value is not None else {}) is None
+
+
+class TestFill:
+    async def test_archives_made_before_get_theirs_once(self, files, db_session, test_engine, off_the_loop):
+        _three_mf(files / DIR / "a.gcode.3mf")
+        older = PrintArchive(filename="a.gcode.3mf", file_path=f"{DIR}/a.gcode.3mf", file_size=1)
+        gone = PrintArchive(filename="gone.3mf", file_path=f"{DIR}/gone.3mf", file_size=1)
+        read = PrintArchive(filename="r.3mf", file_path=f"{DIR}/a.gcode.3mf", file_size=1, gcode_hash=NO_GCODE)
+        db_session.add_all([older, gone, read])
+        await db_session.commit()
+
+        sessions = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
+        assert await fill_gcode_hashes(sessions, batch=1) == 2
+        assert await fill_gcode_hashes(sessions) == 0
+
+        for row in (older, gone, read):
+            await db_session.refresh(row)
+        fingerprint = gcode_fingerprint(files / DIR / "a.gcode.3mf")
+        assert (older.gcode_hash, gone.gcode_hash, read.gcode_hash) == (fingerprint, NO_GCODE, NO_GCODE)
+        assert archive_gcode_hash.read_gcode_hash in off_the_loop
+
+    async def test_an_archive_read_meanwhile_keeps_what_was_read(self, files, db_session, test_engine, monkeypatch):
+        racing = PrintArchive(filename="a.gcode.3mf", file_path="", file_size=0)
+        db_session.add(racing)
+        await db_session.commit()
+        sessions = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
+
+        async def meanwhile(fn, row):
+            # Its 3MF recovered and read while the fill reads it.
+            async with sessions() as other:
+                (await other.get(PrintArchive, racing.id)).gcode_hash = "f" * 64
+                await other.commit()
+            return fn(row)
+
+        monkeypatch.setattr(archive_gcode_hash, "asyncio", SimpleNamespace(to_thread=meanwhile))
+
+        assert await fill_gcode_hashes(sessions) == 0
+        await db_session.refresh(racing)
+        assert racing.gcode_hash == "f" * 64

+ 1 - 0
backend/tests/integration/test_pause_load_paths_2984.py

@@ -54,6 +54,7 @@ async def _start_from_cache(test_engine, printer_id: int, cached) -> None:
         pm.get_status = MagicMock(return_value=state)
         pm.get_printer = MagicMock(return_value=MagicMock(serial_number="TESTAP2"))
         pm.get_client = MagicMock(return_value=None)
+        pm.get_current_print_user = MagicMock(return_value=None)  # a print nobody started in Bambuddy
 
         from backend.app.main import on_print_start
 

+ 359 - 0
backend/tests/integration/test_slicer_resend_joins_archive_1634.py

@@ -0,0 +1,359 @@
+"""The same slice sent again from the slicer adds a run to its archive (#1634).
+
+A slicer sending a slice again writes a new 3MF around the same G-code, so the
+file's hash never matched and each send became an archive of its own, its
+print count stuck at one. A print sent from the slicer whose G-code matches an
+archive (same owner, no project, no File Manager file) now joins that archive:
+the archive takes the new file in place of its old one and opens this print's
+run on it.
+"""
+
+from __future__ import annotations
+
+import zipfile
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from sqlalchemy import select
+
+from backend.app.core.config import settings as app_settings
+from backend.app.models.archive import PrintArchive
+from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
+from backend.app.services import archive_work
+from backend.app.services.archive import ArchiveService
+from backend.app.services.archive_gcode_hash import gcode_fingerprint
+from backend.tests.integration.test_external_print_confirmation_1898 import (
+    _clear_print_state,  # noqa: F401 - autouse fixture
+    _drive_print_start,
+)
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.integration]
+
+GCODE = b"; HEADER_BLOCK_START\nG28\nG1 X10 Y10 F3000\n"
+
+
+def _sliced(path, gcode: bytes = GCODE, *, export: str = "first"):
+    """A sliced 3MF; ``export`` stands for what a new export of it changes."""
+    path.parent.mkdir(parents=True, exist_ok=True)
+    with zipfile.ZipFile(path, "w") as zf:
+        zf.writestr("3D/3dmodel.model", f"<model export='{export}'/>")
+        zf.writestr("Metadata/plate_1.gcode", gcode)
+    return path
+
+
+@pytest.fixture
+def files(tmp_path, monkeypatch):
+    monkeypatch.setattr(app_settings, "base_dir", tmp_path)
+    monkeypatch.setattr(app_settings, "archive_dir", tmp_path / "archive")
+    return tmp_path
+
+
+async def _archived(db_session, printer_id: int, files, *, name: str = "Bracket.3mf", **fields) -> PrintArchive:
+    """The archive of the first send, printed and done."""
+    archive = await ArchiveService(db_session).archive_print(printer_id, _sliced(files / "first" / name))
+    for key, value in {"status": "completed", **fields}.items():
+        setattr(archive, key, value)
+    await db_session.commit()
+    return archive
+
+
+async def _send_again(test_engine, printer, files, gcode: bytes = GCODE, *, owner_id: int | None = None):
+    """The slicer sends a print; the printer's 3MF is a new export of ``gcode``."""
+    upload = _sliced(files / "upload" / "sent.3mf", gcode, export="again")
+
+    async def download(_ip, _code, _remote, local_path, **_kwargs):
+        local_path.write_bytes(upload.read_bytes())
+        return True
+
+    return await _drive_print_start(
+        test_engine,
+        printer,
+        download_ok=True,
+        extra_patches=(
+            patch("backend.app.main.download_file_async", new=AsyncMock(side_effect=download)),
+            patch("backend.app.main.ArchiveService", ArchiveService),
+            patch("backend.app.main._ask_outcome_for_external_print", new=AsyncMock(return_value=False)),
+            patch("backend.app.main._print_user_id_if_still_there", new=AsyncMock(return_value=owner_id)),
+        ),
+    )
+
+
+async def _archives(db_session) -> list[PrintArchive]:
+    db_session.expire_all()
+    return list((await db_session.scalars(select(PrintArchive).order_by(PrintArchive.id))).all())
+
+
+async def _open_runs(db_session, archive_id: int) -> list[PrintLogEntry]:
+    return list(
+        (
+            await db_session.scalars(
+                select(PrintLogEntry)
+                .where(PrintLogEntry.archive_id == archive_id, PrintLogEntry.status == RUN_OPEN)
+                .execution_options(**{INCLUDE_OPEN_RUNS: True})
+            )
+        ).all()
+    )
+
+
+class TestJoining:
+    async def test_the_same_slice_sent_again_adds_a_run_to_its_archive(
+        self, test_engine, db_session, printer_factory, files
+    ):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.id == archive.id
+        assert row.status == "printing"
+        assert len(await _open_runs(db_session, archive.id)) == 1
+        from backend.app.main import _active_prints
+
+        assert archive.id in _active_prints.values()
+
+    async def test_it_takes_the_new_file_into_its_own_folder(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+        folder = (files / archive.file_path).parent
+        old_file = files / archive.file_path
+        photo = folder / "photos" / "finish.jpg"
+        photo.parent.mkdir()
+        photo.write_bytes(b"jpg")
+        old_hash = archive.content_hash
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        new_file = files / row.file_path
+        assert new_file.parent == folder
+        assert new_file.is_file() and new_file != old_file
+        assert not old_file.exists()
+        assert photo.exists()
+        assert row.content_hash != old_hash
+        assert row.gcode_hash == gcode_fingerprint(new_file)
+
+    async def test_another_slice_is_archived_anew(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        await _send_again(test_engine, printer, files, GCODE + b"G1 Z0.2\n")
+
+        rows = await _archives(db_session)
+        assert len(rows) == 2
+        assert rows[0].id == archive.id and rows[0].status == "completed"
+
+    @pytest.mark.parametrize("which", ["project", "library file", "deleted"])
+    async def test_an_archive_that_is_not_the_slicers_is_not_joined(
+        self, test_engine, db_session, printer_factory, files, which
+    ):
+        from backend.app.models.library import LibraryFile
+        from backend.app.models.project import Project
+
+        printer = await printer_factory()
+        fields: dict = {}
+        if which == "project":
+            project = Project(name="Brackets")
+            db_session.add(project)
+            await db_session.commit()
+            fields["project_id"] = project.id
+        elif which == "library file":
+            lib = LibraryFile(filename="Bracket.3mf", file_path="library/Bracket.3mf", file_size=1, file_type="3mf")
+            db_session.add(lib)
+            await db_session.commit()
+            fields["library_file_id"] = lib.id
+        else:
+            fields["deleted_at"] = datetime.now(timezone.utc)
+        await _archived(db_session, printer.id, files, **fields)
+
+        await _send_again(test_engine, printer, files)
+
+        assert len(await _archives(db_session)) == 2
+
+    async def test_the_owner_has_to_match(self, test_engine, db_session, printer_factory, files):
+        from backend.app.models.user import User
+
+        user = User(username="maker", password_hash="x", role="user")
+        db_session.add(user)
+        await db_session.commit()
+        user_id = user.id
+        printer = await printer_factory()
+        owned = await _archived(db_session, printer.id, files, created_by_id=user_id)
+        owned_id = owned.id
+
+        # Nobody started this print: the owned archive is not its.
+        await _send_again(test_engine, printer, files)
+        assert len(await _archives(db_session)) == 2
+
+        # Its owner started the next one, once that print ended.
+        from sqlalchemy import update
+
+        await db_session.execute(update(PrintArchive).values(status="completed"))
+        await db_session.execute(
+            update(PrintLogEntry).values(status="completed").execution_options(**{INCLUDE_OPEN_RUNS: True})
+        )
+        await db_session.commit()
+        await db_session.refresh(printer)
+        await _send_again(test_engine, printer, files, owner_id=user_id)
+        rows = await _archives(db_session)
+        assert len(rows) == 2
+        assert len(await _open_runs(db_session, owned_id)) == 1
+
+    async def test_an_archive_being_merged_is_left_alone(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        with archive_work.merging([archive.id]):
+            await _send_again(test_engine, printer, files)
+
+        assert len(await _archives(db_session)) == 2
+        assert not archive_work.is_held(archive.id)
+
+    async def test_the_archive_is_released_once_its_run_is_open(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        await _send_again(test_engine, printer, files)
+
+        assert not archive_work.is_held(archive.id)
+
+
+class TestPrintingElsewhere:
+    async def test_the_file_another_print_reads_is_kept(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        other = await printer_factory(name="Other")
+        archive = await _archived(db_session, printer.id, files, status="printing")
+        old_file = files / archive.file_path
+        old_hash = archive.content_hash
+        db_session.add(
+            PrintLogEntry(
+                archive_id=archive.id,
+                printer_id=other.id,
+                status=RUN_OPEN,
+                print_name=archive.print_name,
+                started_at=datetime.now(timezone.utc),
+            )
+        )
+        await db_session.commit()
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert (row.content_hash, row.file_path) == (old_hash, archive.file_path)
+        assert old_file.exists()
+        assert len(await _open_runs(db_session, archive.id)) == 2
+
+
+class TestName:
+    async def test_a_name_the_file_gave_follows_the_file(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files, name="Old_name.3mf")
+        assert archive.print_name == "Old_name"
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.print_name == "Bracket_plate_1"  # the name of the file the printer had
+
+    async def test_a_name_set_by_hand_stays(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        await _archived(db_session, printer.id, files, name="Old_name.3mf", print_name="Wall bracket, left")
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.print_name == "Wall bracket, left"
+
+
+class TestWhatTheArchiveKeeps:
+    async def test_the_saved_ams_pick_stays(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        pick = {"mapping": [0, 2], "printer_id": printer.id}
+        await _archived(db_session, printer.id, files, extra_data={"slicer_ams_mapping": pick})
+
+        await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert row.extra_data["slicer_ams_mapping"] == pick
+
+    async def test_a_copy_that_fails_its_check_leaves_the_old_file(
+        self, test_engine, db_session, printer_factory, files
+    ):
+        """Same file name: the copy goes to a temporary name first, so a
+        truncated one never lands on the archive's file."""
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files, name="Bracket_plate_1.gcode.3mf")
+        old_file = files / archive.file_path
+        old_bytes = old_file.read_bytes()
+
+        def truncated(_src, dst, *_args, **_kwargs):
+            dst.write_bytes(b"not a zip")
+
+        with patch("backend.app.services.archive._copy_and_fsync", side_effect=truncated):
+            await _send_again(test_engine, printer, files)
+
+        (row,) = await _archives(db_session)
+        assert (row.file_path, row.content_hash) == (archive.file_path, archive.content_hash)
+        assert old_file.read_bytes() == old_bytes
+        assert len(await _open_runs(db_session, archive.id)) == 1
+
+    async def test_a_file_a_queue_dispatch_holds_is_kept(self, test_engine, db_session, printer_factory, files):
+        """A queue dispatch holding the archive uploads or prints its file: the
+        resend adds its run but does not take the file away under it."""
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+        old_file = files / archive.file_path
+
+        archive_work.hold(archive.id)
+        try:
+            await _send_again(test_engine, printer, files)
+            assert archive_work.is_held(archive.id), "the dispatch's hold is its own"
+        finally:
+            archive_work.release(archive.id)
+
+        (row,) = await _archives(db_session)
+        assert row.file_path == archive.file_path
+        assert old_file.exists()
+        assert len(await _open_runs(db_session, archive.id)) == 1
+
+
+class TestEvents:
+    async def test_a_joined_archive_is_updated_not_created(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+
+        mocks = await _send_again(test_engine, printer, files)
+
+        mocks["ws_manager"].send_archive_created.assert_not_awaited()
+        mocks["mqtt_relay"].on_archive_created.assert_not_awaited()
+        (event,), _ = mocks["ws_manager"].send_archive_updated.await_args
+        assert event["id"] == archive.id
+
+    async def test_a_new_archive_is_created(self, test_engine, db_session, printer_factory, files):
+        printer = await printer_factory()
+
+        mocks = await _send_again(test_engine, printer, files)
+
+        mocks["ws_manager"].send_archive_created.assert_awaited_once()
+        mocks["mqtt_relay"].on_archive_created.assert_awaited_once()
+
+
+class TestPrinterDeleted:
+    async def test_a_joined_archive_is_not_removed_as_one_just_written(
+        self, test_engine, db_session, printer_factory, files
+    ):
+        """The check after writing removes an archive this start wrote for a
+        printer deleted meanwhile. A joined archive is not this start's: it
+        holds earlier runs, and its adoption checked the printer itself."""
+        printer = await printer_factory()
+        archive = await _archived(db_session, printer.id, files)
+        drop = AsyncMock(return_value=True)
+
+        with patch("backend.app.main._drop_archive_of_deleted_printer", drop):
+            await _send_again(test_engine, printer, files)
+
+        drop.assert_not_awaited()
+        (row,) = await _archives(db_session)
+        assert row.id == archive.id
+        assert len(await _open_runs(db_session, archive.id)) == 1