DEV Community

Cover image for Detect Product ID Collisions Before Normalizing a 2scraper Export
gresiuseo
gresiuseo

Posted on Edited on

Detect Product ID Collisions Before Normalizing a 2scraper Export

When I test a new 2scraper export adapter, I keep the identifier exactly as supplied until I can prove what a proposed cleanup would merge. A padded ID can look untidy. Trimming it can also hide a distinct product that legitimately carries a leading space in a historical namespace. I want the importer to expose the two original values and the common proposed key while the decision is still reversible.

I ran the Python fixture locally with invented records. It represents an internal reporting contract. The article and cover were prepared with AI assistance.

Preserve the original identity through parsing

An identifier is a string in this example. Its characters and expected namespace are part of the record. If the adapter asks a spreadsheet to infer types, it can turn a padded numeric string into an integer while the other fields remain valid. A parser regression test should discover an identifier that changed between the approved input and the imported row, even when the row count is unchanged.

Treat the candidate lookup key as a separate derived value. Keep the original string and source namespace next to it. I would enable proposed normalization only in a review view until somebody authorized to define identity confirms which equivalent forms describe one product. The source namespace matters because the same string might identify unrelated products in two independently managed catalogs.

The sample deliberately tries space trimming, compatibility normalization and case folding together to surface conflicts. These rules are useful to evaluate as a proposal. Production equivalence rules may allow only one of them or restrict them to specific namespaces. Record both the proposal and the approved behavior so that a reviewer can repeat the decision without relying on current defaults.
Enter fullscreen mode Exit fullscreen mode

Choose a single reasonable unit of work for the normalizer and document how the dataset namespace and original product identifier identifies it. Keep the incoming evidence available to the people allowed to review it. In the derived view, store the accepted value, the mapping rule, its version and the reason for any excluded instance. The catalog reviewer can then follow a surprising value back to the raw identifier, its source namespace and the exact revision of the key mapping without guessing which transformation introduced it.

Write a complete positive case and one plausible counterexample in the handoff documentation. Both should have the dataset namespace and original product identifier, the same intended scope and an observable result in the product identity review table. A future editor may preserve the row layout while changing the definition that drives the decision. State the definition as an input contract and test it independently from the layout. For a historic review, identify the exact method that produced the released number before running a newer method.

Run the collision check on two imaginary catalogs

The sample includes the text identifier 0017, plus a Latin label in two deliberate spellings. The collisions are checked separately for each catalog scope. A missing candidate is rejected with the source identity still available for review.

from collections import defaultdict
from unicodedata import normalize

rows = [("A", "0017"), ("A", "17"), ("A", " Sale"),
        ("A", "SALE"), ("A", "sale"), ("B", "sale"), ("B", " ")]
by_key = defaultdict(set)
rejected = []
for catalog, original in rows:
    candidate = normalize("NFKC", original).strip().casefold()
    if candidate:
        by_key[(catalog, candidate)].add(original)
    else:
        rejected.append((catalog, original))
collisions = {k: sorted(v) for k, v in by_key.items() if len(v) > 1}
assert len(collisions) == 1
assert set(collisions[("A", "sale")]) == {" Sale", "SALE", "sale"}
assert ("A", "0017") in by_key and ("A", "17") in by_key
assert rejected == [("B", " ")]
print("A sale has 3 original forms; 1 blank candidate held; numeric IDs remain distinct")
Enter fullscreen mode Exit fullscreen mode

The local run printed the following result.

A sale has 3 original forms; 1 blank candidate held; numeric IDs remain distinct
Enter fullscreen mode Exit fullscreen mode

The fixture finds one collision with three different raw values, and the independent B catalog keeps its sale key outside the conflict. Candidate 0017 remains distinct from candidate 17 because this comparison never parses identifiers as numbers. A blank candidate reaches review. Record the count of unique raw forms and a separate count of their occurrences if multiple export rows can carry one original identifier.

Before you run the comparison again, record the raw identifier, its source namespace and the exact revision of the key mapping along with the fixture revision. A passing check tells the reviewer how this exact sample behaved under the named policy. If the sample changes, keep that change in review with the expected result. I would give a second reader the fixture and ask them to predict the number and membership of collision groups from the input before executing the test. That exercise exposes missing assumptions a green process exit can leave implicit.

Walk through a collision that row counts cannot explain

Give a teammate five invented source rows and ask them to count products before a normalized key is available. Then treat two apparently different values as equal in the candidate index. The number of input rows remains five. The join may now produce fewer matches or distribute one enrichment value across multiple original products.

The acceptance test should observe both the candidate collision membership and the original source identities in the report. A target row count can remain the same if a join expands a second group at the same time. Independent checks of distinctness and mapping membership catch both effects.

For the reviewer, an evidence row should contain the common candidate, both original forms and the name of the rule that made them equal. Keep a stable source locator. Two labels rendered with a similar plain-text appearance can otherwise produce an unhelpful review table.

Try a visually invisible difference

One raw export can include a nonbreaking space or the ASCII space it resembles. Decide whether they have the same meaning in the approved identity contract. Their snapshots can appear identical in the workbook view. Build synthetic identifiers with explicit escaped representations and use them to test whether the candidate rule trims or preserves each one.

The reviewer needs an inspection view that exposes the difference without changing the raw stored key. Show an escaped representation or character codes next to the human-friendly label on the test data. Preserve which operation caused the collision, because case handling and space cleanup may have been approved at different times.

A small case with a nonbreaking space also checks text export behavior. Reopen the output in the tool that normally consumes it and verify what happens to the stored representation. The collision detector can be correct while a later CSV-to-workbook handoff silently modifies the accepted identifiers.

Keep a row duplicate separate from an identity collision

Imagine an identical source row arrives twice during a transfer resumption. Both copies carry the same key and the same observation. A different event carries a new observation for the same product at a later time. Neither is the example in which two distinct raw identifiers collapse through a candidate mapping.

Give each condition an explicit test. An ingestion duplicate calls for a policy about transport identity. An observation refresh calls for a policy about time and record scope. A candidate identity collision calls for a decision about equivalence. The counts and evidence for the three cases should remain independent so somebody can resolve the actual issue.

Model a conflict in which the same raw ID has two different product descriptions in one delivery. Retain both input rows in the evidence and surface their source provenance. Choosing a normalized candidate key does not decide which observation carries the authoritative description.

Test both sides of a join

Build the smallest fixture that joins an approved catalog and a derived review output. Put leading zeros on IDs in both. Import one side as text and intentionally pass the other through a numeric conversion in a disposable test. The resulting mismatch illustrates why checks on the original catalog alone cannot establish that the entire handoff preserved identity.

Add another input that falls into a candidate group on only one side. Check for explicitly missing, multiple and unique matches. An inner join can hide missing keys by dropping them. A report that labels missing matches helps a teammate distinguish a real absence from the wrong normalization rule.

Retain a list of source and destination identities for disputed matches under the approved data policy. After a rule update, compare the old and new join outputs on the same fixture so a reviewer can see exactly which product association changed.

Choose a fallback before switching lookup rules

A downstream catalog may need to continue serving the last approved report while a candidate group is blocked. Keep the last released dataset available with its as-of time. Expose a review count for the newer candidate and identify affected namespaces. That preserves a clear operational choice for readers who need a current value.

An approved equivalence can be expressed as an explicit alias map keyed by the original identity. Document its effective date and check that it cannot point to two products under the same namespace. A second conflict test should show what happens when an old alias is reassigned. Give the old released output a stable identity so it can still be investigated.

Once a mapping has been approved, verify that it can be replayed without changing original records. The accepted publication should refer to the selected mapping revision. If the rule is rolled back, historical screenshots and summaries should still be traceable to the revision used when they were released.

Review a mapping proposal with a reproducible old and new output

The same approved input can productively run through two mappings during a review. Build a difference table keyed by the raw identity and label each row whose candidate changed. Link the old and new candidate values to the specific normalization stage so somebody can approve a constrained change. Keep a count of newly eligible, newly held and unchanged records. It is easier to review a mapping that shows who would be affected before it becomes a required part of a normal import.

Agree how to preserve a revision for people who still depend on a historical key. A named v1 alias map can continue serving a reproducible workbook while a revised v2 map has a limited pilot. Choose a migration boundary and decide who can accept the changed resolution. A controlled disagreement between two reports can be explained when both versions state their mapping explicitly.
Enter fullscreen mode Exit fullscreen mode

Put the current source, accepted output, and released version side by side for a small review. The source view should show the raw identifier, its source namespace and the exact revision of the key mapping. The accepted output should show the number and membership of collision groups under a declared version. The released view should show which catalog records can join the report and the scope on which it depends. The three views make it possible to find the first point at which two analysts disagree. Keep at least one disputed synthetic row so you can verify the process even when real records are unavailable.

Change one assumption at a time in a disposable copy. First rerun the same data under the same method and expect an identical result. Next modify just one reviewed input and check only the affected identities. Finally rerun the original data with the proposed method. Explain the movement in the number and membership of collision groups by reference to the changed input or rule. If both changed together, ask for two intermediate runs so that an apparent regression can be attributed to a specific change. Store the effective dates of both sources and methods in the review note.

Ask an independent reviewer to follow one conflict

Give the reviewer three expected outcomes from the toy run. The three forms of sale collide in catalog A, the same term in catalog B stays independent, and 0017 stays distinct from 17. Ask them to identify which assumption makes each outcome hold. Then show them a raw value represented with escape sequences and ask them to find the corresponding row in the review output. This validates that the evidence is legible without silently changing the data shown.

A useful test note names the original file, namespace, attempted identity mapping and accepted disposition. It also says which downstream report still references the old mapping. This is as important as a passing code assertion when a real conflict prevents one team from releasing an update.
Enter fullscreen mode Exit fullscreen mode

Test the explanation as part of the handoff. Give the catalog reviewer a screenshot of the product identity review table, the approved fixture and access to the method note. Ask them to reproduce the number and membership of collision groups and describe which evidence would cause them to revisit which catalog records can join the report. If they succeed only after opening the script, move the relevant scope and rule into the report. The person making the decision should be able to check its basis using artifacts they normally receive.

Write a separate release check covering the case where the correct outcome must remain pending. Show the count of records held, their affected scope and the transition that would allow them into the next calculation. Keep daily operations legible by distinguishing a successfully classified row from one that is waiting for a decision. A reviewer should be able to trace either state using the dataset namespace and original product identifier and reopen the exact case when new evidence arrives.

Before wiring 2scraper data into your catalog, run this review over a synthetic slice with leading zeros, distinct spellings and two independent namespaces. Preserve the original IDs and share one collision group with the maintainer who decides equivalence. Add their agreed outcome to a repeatable fixture before converting the derived key into a live join field.

Further reading

Verify the Exact Product Set in a Filtered 2scraper Export shows how to compare membership using the accepted identities.

Keep Parent Product IDs Out of an Amazon Scraper Variant Price Join works through product and variant grain before joining prices.

Normalize Package Dimensions Before Comparing an Amazon Export. This example applies a similar raw-versus-derived distinction to physical measurements.

Top comments (0)