DEV Community

Cover image for Advance a 2scraper Import Checkpoint Only After the Page Is Committed
gresiuseo
gresiuseo

Posted on

Advance a 2scraper Import Checkpoint Only After the Page Is Committed

A reproducible SQLite failure shows how row storage and progress can commit together.

When I import a local export associated with 2scraper, the progress number is a promise about data that can be reopened after a failure. A cursor that already says page two is done is dangerous if the worker died just before it stored page two's rows. Here is a small reproduction that can detect that gap without connecting to other sites.

Prepared with AI assistance. I ran the Python example locally with fictional records. It tests the stated assumptions for a downstream workflow.

Reproduce the skipped page before changing the job

I start with three ordinal pages. The report already contains the first page. The second page carries two records. The third page is valid and unrelated. A crash during the second page is the case that matters because a successful third page can hide the omitted records in a normal daily totals chart. It also shows the difference between a worker doing some work and a report being allowed to claim the whole page.

A writer that persists its cursor before rows effectively tells the next process to skip anything through the cursor. A writer that commits rows first and then stores the cursor might replay valid work the next time. Idempotent row keys can reduce the effect of replay but the log still has an ambiguous boundary. Putting the writes together gives the restart process one durable observation. That boundary survives logging or display failures.

Treat the run identifier as part of cursor identity

The cursor in this example is a monotonic ordinal within one finished export. A second export can also have a page two. I would associate the durable cursor with the ordered snapshot or artifact identifier. If an operator swaps the input manifest and tries a retry, detect the mismatch before interpreting any ordinal. A cursor from another snapshot cannot meaningfully describe existing records.

Each page has an expected predecessor. A worker presenting a page beyond the next ordinal may have skipped an input or picked up a page assigned to a different worker. Refuse it and leave the job available for diagnosis. If you genuinely need independent page handling, use a per-page accepted state with unique identifiers. A single maximum number can hide gaps in an out-of-order list.

A page accepted earlier must be reconstructible. The sample replay is an identical local packet. In a general import I would retain a digest over the immutable page bytes and validate each repeated page against the recorded digest before treating it as equivalent. If the same ordinal yields different bytes for a closed export, report the disagreement and keep both references for review.

Make the crash happen after the insert

This standard-library example initializes its schema in a new on-disk database. The connection is closed after the simulated failure and the subsequent assertions use a new connection. That matters because a short-lived in-memory transaction might demonstrate rollback inside one process without checking what a restarted process actually sees.

import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory

def put_page(db, ordinal, rows, crash=False):
    with db:
        db.execute("BEGIN IMMEDIATE")
        current = db.execute("SELECT ordinal FROM cursor").fetchone()[0]
        if ordinal <= current:
            return False
        if ordinal != current + 1:
            raise ValueError("page gap")
        db.executemany("INSERT INTO products VALUES (?, ?)", rows)
        if crash:
            raise RuntimeError("simulated crash after rows")
        db.execute("UPDATE cursor SET ordinal = ?", (ordinal,))
        return True

def snapshot(db):
    return (db.execute("SELECT ordinal FROM cursor").fetchone()[0],
            db.execute("SELECT COUNT(*) FROM products").fetchone()[0])

with TemporaryDirectory() as tmp:
    path = Path(tmp) / "catalog.sqlite"
    db = sqlite3.connect(path)
    db.executescript("""
        CREATE TABLE cursor (ordinal INTEGER NOT NULL);
        INSERT INTO cursor VALUES (0);
        CREATE TABLE products (source_id TEXT PRIMARY KEY, label TEXT);
    """)
    assert put_page(db, 1, [("A", "Anvil")])
    second = [("B", "Book"), ("C", "Clock")]
    try:
        put_page(db, 2, second, crash=True)
    except RuntimeError:
        pass
    else:
        raise AssertionError("failure was not injected")
    db.close()
    db = sqlite3.connect(path)
    assert snapshot(db) == (1, 1)
    assert put_page(db, 2, second)
    assert not put_page(db, 2, second)
    assert snapshot(db) == (2, 3)
    try:
        put_page(db, 4, [("D", "Desk")])
    except ValueError:
        assert snapshot(db) == (2, 3)
    else:
        raise AssertionError("gap accepted")
    db.close()
    print("After reopen: page 1, 1 row. After retry: page 2, 3 rows.")
Enter fullscreen mode Exit fullscreen mode

A local execution printed the following result.

After reopen: page 1, 1 row. After retry: page 2, 3 rows.
Enter fullscreen mode Exit fullscreen mode

The failure in the fixture happens after inserting two page-two rows but before updating progress. Reopening recovers page one and one data row. A retry completes page two, and the duplicate replay leaves the total unchanged. All three steps are asserted. The final page count of two says nothing about page three, which has deliberately never been ingested in the test.

The sample assumes a single writer and immutable local page packets. In a many-worker pipeline, make the selected export identity and predecessor part of the transaction's read condition. SQLite can serialize the write transactions with BEGIN IMMEDIATE. Separate staging jobs that write into the same report need a broader coordination rule, especially if final reports are replaced in a different storage system.

Inject a failure where success usually seems inevitable

Testing only an exception before the database is opened misses the important boundary. It tells you that a broken payload fails before it mutates state. I ask a reviewer to call out the exact point between the row writes and the cursor write, then inject a failure there. Next run a clean retry and check the first and last record of the formerly interrupted page. A report can show the correct total even when one inserted record replaced another, so compare identities as well as counts before release.

Clarify what an empty approved page means

Some exports allow an empty page between two nonempty pages. Mark it as accepted only if the manifest says that page exists with zero records. An empty packet with missing headers differs from a legitimate empty sequence of rows. The checkpoint can advance on the latter and should wait on the former. I would record the header specification and explicit row count before committing. If the contract only produces the final empty page, preserve its relationship to run completion instead of fabricating an ordinal after it.

Keep cursor advancement independent from notification delivery

A progress message sent to a dashboard can fail after the commit. The durable cursor should still reflect what the database accepted. If the report needs a downstream notification, persist an outbox row within the same accepted transaction and let the notifier replay independently. Hold the notification identifier stable so the consumer can ignore duplicate deliveries. A test that fakes database success and notification failure demonstrates why the dashboard must be based on accepted records when an operator refreshes it.

Avoid conflating quarantine with incomplete processing

A page with a known invalid record can be accepted under a policy that explicitly writes that row to quarantine and excludes it from the reporting table. A crashed transaction cannot claim that it quarantined anything. Decide beforehand whether the entire page is atomic or whether a page can have separate accepted and rejected rows. If the latter, write the per-row decision and source count together. The progress label can then distinguish completed with review items from replay required.

Make an interrupted import easy to inspect

The handoff view I would build lists the export identity, expected pages, last committed ordinal and count of records in accepted and quarantine sets. Include a pointer to the manifest and the timestamps of last successful commit and last worker attempt. Those two times can diverge during an outage. A worker retry should leave enough evidence to resolve whether the input or the commit boundary stopped progress.

Give the on-call reader one stable query that returns the accepted page set and snapshot identity before they issue a replay. If they discover a database with types from a newer schema, let the job refuse the incompatible read until a migration decision is made. Running a repair command on the wrong export is harder to unwind than a single stopped job.

Exercise the same logic through the normal ingest entry point during a dry run. Arrange that release validation first executes the fixture on a clean file and then runs the regular process with one disposable input. Capture the observed database cursor from each. That last step spots a case where the tested helper behaves properly but the real entry point writes its own progress in a separate place.

Use a regression check that survives a restart

I would ask the reviewer to identify the invariant in one sentence. For a sequential manifest, every page through the last committed ordinal has a durable disposition in this run. Given an interrupted page, the next worker knows which ordinal is the first unresolved one. Validate that invariant after restart, when work is resumed from different process memory.

Document what the replay function treats as idempotent. If the promised idempotent identity is the artifact hash and ordinal, make both visible in the assertion. Save the old failure reproduction next to the fixed expected result, with dates from stable synthetic inputs. That lets a future migration prove it preserves both interruption and gap behavior.

Send one interrupted run through release review

I would make the first review from an ordered three-page manifest and a new copy of the SQLite file. Have one person perform the review from an untouched export of the fixture and have another person run the example. Compare their explanations of committed ordinal and accepted product identities before comparing any rounded number or success badge. An agreement on the final display can hide a disagreement about which input rows belong in the reported population. If the two explanations differ, trace the first decision in the write transaction and the predecessor check that separates them. That makes a repeatable check out of an argument about which output looks familiar.

Save an example where the difference is small enough to escape casual review, then put its input next to an ordered three-page manifest and a new copy of the SQLite file. Separate the evidence the operator was able to obtain from an assumption made by the reporting code. The reviewer should be able to identify what an apparent success for a page separated by a gap looks like in the input before learning how the program reports it. For the failed example, write down which output would be misleading and which evidence would allow a later review to resolve the case.

The release evidence I would ask the operator responsible for replay to keep is the input reference, the effective rule and the observed committed ordinal and accepted product identities. A short explanation alongside those fields helps when a later change affects only one reader or time period. Append the evidence to the release note for the small change that produced it. That gives future operators a place to ask whether the output they see today was already possible in the previous release. Keep a stable label for the expected failure case even if the note, export layout or display title changes.

Finally, replay the same inputs in a clean workspace. Re-create the derived evidence before looking at a copy from the earlier run. If the second workspace cannot reproduce committed ordinal and accepted product identities, record which input, time boundary or method version was missing. A third reviewer should be able to distinguish a discrepancy in an ordered three-page manifest and a new copy of the SQLite file from a discrepancy in the write transaction and the predecessor check. That check is most valuable when the normal system continues running and presents a plausible value after one dependency changes.

Rehearse one failure on a local export

Take a completed local export from 2scraper and stage only a small copy for the rehearsal. Interrupt the transaction after it consumes two fixture rows, close the connection, and replay on a new one. Keep the checkpoint and its run identity in the test output so the person reviewing the next import can reproduce the decision.

Further reading

Verify the Exact Product Set in a Filtered 2scraper Export Use that set check after a completed import.

Detect Product ID Collisions Before Normalizing a 2scraper Export Run the identity check before writing rows to the stable table.

Keep a Late Catalog Import From Overwriting a Newer Snapshot Apply that revision rule when a previously seen item arrives with newer evidence.

Top comments (0)