Package availability: JaviMapper is an unpublished beta and JaviPerf is experimental. Neither has a public PyPI release or public wheel, and the source repository is private. Visitors cannot obtain or build these packages from this site. The Fabric installation steps below require an already-authorized wheel supplied privately; without that access, the exercises cannot be run.

Hands-on: reconcile three merchant schemas

Microsoft Fabric is the primary execution path. Install the private JaviMapper 0.6.0b1 wheel in a dedicated Fabric Environment, attach a Lakehouse containing three fictional merchant CSVs, and run the six exercises in the existing notebook. The local path remains optional.

  1. Build private wheel
  2. Publish Fabric Environment
  3. Attach notebook and Lakehouse
  4. Review and apply mappings
  5. Inspect report and effort
Prepare a private wheel and Fabric Environment, then run reviewed mappings against synthetic Lakehouse files.

Prerequisites

Check current versions and lifecycle in Fabric Spark runtimes and Runtime 2.0.

Download the wheel

Open Microsoft Fabric and create a dedicated lab workspace and Environment. In the Environment, upload the downloaded wheel under Custom libraries, save, and Publish. Attach the published Environment to this lab notebook, start a new session, and verify import javimapper; print(javimapper.__version__) returns 0.6.0b1. Continue with the setup below. The link works only in the local JaviBuilds development server. This private wheel is not published to PyPI and must not be copied into website assets.

Create a Fabric Environment

In the dedicated lab workspace, select + New → Environment, create a lab-specific item, and open its Spark compute settings. Choose a runtime only after comparing its Python, Spark, pandas and PySpark versions with the library requirements. A pure-Python wheel avoids compiled-wheel ABI constraints, but its PySpark adapter still depends on Fabric’s compatible Spark/PySpark runtime.

Do not infer compatibility from a runtime name. If the package fails its import or adapter checks, choose a supported runtime or request a compatible library build. Do not force-upgrade Fabric-managed Spark dependencies with %pip or an Environment override without a compatibility test.

Upload and publish library

In the Environment’s Libraries area, choose Custom libraries, upload the local .whl, save, and select Publish. Choose the publish mode offered by Fabric; Full creates a stable dependency snapshot and can take longer than Quick. Wait for publishing to finish and confirm the library status. See Microsoft’s library management and Environment setup guides.

If publishing or dependency resolution reports a conflict, save the complete error and compare it with the selected runtime’s built-in package versions. Do not change pandas or PySpark blindly. Use a runtime whose built-ins satisfy the requirements or a JaviMapper build validated for that runtime.

Attach Environment

Create or open a Fabric Spark notebook, select the new Environment in its Environment selector, and confirm. Start a new session after attaching or changing it; an existing session does not adopt the new Environment. Run the first cell to verify javimapper.__version__ == "0.6.0b1" and print Python, PySpark and Spark versions. The notebook reuses Fabric’s provided spark session.

Create or attach Lakehouse

Create a dedicated lab Lakehouse or attach an existing lab-only Lakehouse, then make it the notebook’s default. In Lakehouse Explorer create Files/javimapper/input/ and upload north.csv, south.csv and east.csv from labs/javimapper-mapping-lab/data/. Keep the filenames unchanged. The notebook’s first code cell checks that all three files are present.

Fabric Spark notebooks support default-Lakehouse relative paths such as Files/...; pandas can also access the default mount at /lakehouse/default/Files/.... This notebook reads the tiny files with the attached Spark session and converts only these two-row synthetic fixtures to pandas for the pandas adapter. See Load data into a Lakehouse and NotebookUtils file paths.

Use this Lakehouse layout (the onboarding notebook creates the versioned configuration folder):

Files/
└── javimapper/
    ├── input/
    │   ├── north.csv
    │   ├── south.csv
    │   ├── east.csv
    │   └── east_delivery_02.csv
    ├── config/east-market/
    │   ├── approved-mapping-v1.json
    │   └── east-market-aliases-v1.json  (optional)
    └── output/
        └── mapping-report.html

Import and run notebook

Open labs/javimapper-mapping-lab/notebooks/javimapper-mapping-lab.ipynb in Fabric by uploading or importing it into the lab workspace. Keep EXECUTION_MODE = "fabric", attach the published Environment and default Lakehouse, then select Run all. Its order is: (1) verify Environment and files, then inspect first suggestions; (2) human review and approval; (3) pandas mapping; (4) Fabric Spark mapping; (5) alias reuse across all three schemas; and (6) HTML report generation. The notebook preserves the same five source-to-target mappings and approval safety rules as the local lab.

The screenshots below are evidence captured from the supplied Microsoft Fabric runs; the automated notebook tests are separate local checks. The six-exercise run generated and saved the report, and the supplied capture shows it rendered inline. In Fabric, displayHTML() is the supported HTML-display option when IPython output is not rendered.

Notebook: javimapper-mapping-lab.ipynb

PySpark notebook14 cells

Read-only view of the notebook file. Nothing on this page runs code.

  1. Cell 1MarkdownJaviMapper in Microsoft Fabric: review a mapping from proposal to application

    JaviMapper in Microsoft Fabric: review a mapping from proposal to application

    This notebook is designed for a Fabric Spark notebook attached to a dedicated lab workspace, a published Fabric Environment with the private javimapper==0.6.0b1 wheel, and a default Lakehouse containing the three fictional merchant CSVs. The cells use Fabric’s pre-created spark session. Every row is synthetic. JaviMapper proposes column relationships; a person reviews and approves them before either adapter applies them. A score is a name-similarity heuristic, not a probability.

    Before running: build the wheel locally, upload it to the Environment’s Custom libraries, publish, attach that Environment to this notebook, start a new session, and upload the three CSVs to Files/javimapper/input/. See the accompanying lab page for full steps and compatibility checks. The saved outputs shown here were captured in a local Spark environment; Fabric output has not been observed yet.

    EXECUTION_MODE below defaults to fabric. For the optional local route, set it to local and run from the repository or extracted lab bundle after installing JaviMapper, pandas, PySpark, and Java.

  2. Cell 2MarkdownPrerequisites and Fabric session check
    Prerequisites and Fabric session check

    Confirm the package version, Python/PySpark/Spark versions, active session, and all three Lakehouse files before continuing. If the Fabric check fails, fix the attached and published Environment or Lakehouse rather than installing or replacing packages blindly.

  3. Cell 3PySparkCode61 lines
    PySpark
    from pathlib import Path
    import sys
    import pandas as pd
    import pyspark
    import javimapper
    from javimapper import MatchConfig, Matcher, Schema, render_html
    from javimapper.adapters.pandas import apply_mapping as pandas_apply
    from javimapper.adapters.pandas import schema_from_pandas
    
    EXECUTION_MODE = "fabric"  # change to "local" only for the optional local path
    EXPECTED_VERSION = "0.6.0b1"
    assert javimapper.__version__ == EXPECTED_VERSION, f"Expected {EXPECTED_VERSION}, found {javimapper.__version__}"
    
    if EXECUTION_MODE == "fabric":
        assert "spark" in globals(), "Run this as a Fabric Spark notebook with its provided spark session."
        assert "notebookutils" in globals(), "Attach a default Lakehouse and run in Fabric."
        DATA_DIR = "Files/javimapper/input"
        required_files = {"north.csv", "south.csv", "east.csv"}
        found_files = {item.name for item in notebookutils.fs.ls(DATA_DIR) if item.isFile}
        assert required_files <= found_files, f"Missing Lakehouse files: {sorted(required_files - found_files)}"
    else:
        from pyspark.sql import SparkSession
        cwd = Path.cwd().resolve()
        candidates = [base / relative for base in (cwd, *cwd.parents) for relative in ("labs/javimapper-mapping-lab", ".", "javimapper-mapping-lab")]
        LAB_ROOT = next((path for path in candidates if (path / "data/north.csv").is_file()), None)
        if LAB_ROOT is None:
            raise FileNotFoundError("Could not locate the lab data folder. Run from the repository or extracted bundle.")
        DATA_DIR = str(LAB_ROOT / "data")
        required_files = {"north.csv", "south.csv", "east.csv"}
        found_files = {path.name for path in Path(DATA_DIR).glob("*.csv")}
        assert required_files <= found_files, f"Missing local fixture files: {sorted(required_files - found_files)}"
        if "spark" not in globals():
            spark = SparkSession.builder.master("local[1]").appName("JaviMapperNotebookLab").getOrCreate()
    
    print(f"Execution mode: {EXECUTION_MODE.upper()} (saved outputs were captured locally)")
    print(f"JaviMapper: {javimapper.__version__} | Python: {sys.version.split()[0]} | PySpark: {pyspark.__version__} | Spark: {spark.version}")
    print("Synthetic CSV files found:", ", ".join(sorted(required_files)))
    TARGET = Schema.of(["transaction_id", "transaction_date", "customer_id", "gross_amount", "currency"])
    TRUTH = {
        "north": {"TxnID": "transaction_id", "TxnDate": "transaction_date", "CustomerID": "customer_id", "GrossAmount": "gross_amount", "Currency": "currency"},
        "south": {"transaction_id": "transaction_id", "booked_date": "transaction_date", "buyer_id": "customer_id", "total_amount": "gross_amount", "currency_code": "currency"},
        "east": {"RefNo": "transaction_id", "DateOfSale": "transaction_date", "ClientNo": "customer_id", "SaleValue": "gross_amount", "Currency": "currency"},
    }
    ALIASES = {
        "transaction_id": ["TxnID", "RefNo"],
        "transaction_date": ["TxnDate", "booked_date", "DateOfSale"],
        "customer_id": ["CustomerID", "buyer_id", "ClientNo"],
        "gross_amount": ["GrossAmount", "total_amount", "SaleValue"],
        "currency": ["Currency", "currency_code"],
    }
    def read_source(merchant):
        path = f"{DATA_DIR}/{merchant}.csv"
        if EXECUTION_MODE == "fabric":
            return spark.read.option("header", True).option("inferSchema", False).csv(path).toPandas()
        return pd.read_csv(path, dtype=str)
    
    north = read_source("north")
    first_plan = Matcher().suggest(schema_from_pandas(north), TARGET)
    print("Source | suggested target | method | state")
    for result in first_plan.results:
        print(f"{result.source} | {result.suggested_target or '?'} | {result.method.value if result.method else '?'} | {result.state.value}")

    Output

    Execution mode: LOCAL (saved outputs were captured locally)
    JaviMapper: 0.6.0b1 | Python: 3.12.10 | PySpark: 4.3.0 | Spark: 4.3.0
    Synthetic CSV files found: east.csv, north.csv, south.csv
    Source | suggested target | method | state
    TxnID | transaction_id | normalized | suggested
    TxnDate | transaction_date | normalized | suggested
    CustomerID | customer_id | normalized | suggested
    GrossAmount | gross_amount | normalized | suggested
    Currency | currency | normalized | suggested
  4. Cell 4MarkdownExercise 2 — Human review and approval
    Exercise 2 — Human review and approval

    Bulk approval accepts only the package’s safe default methods. Make an explicit, reasoned decision for any unresolved North Market field. Finalize only after every required target has an approved source.

  5. Cell 5PySparkCode11 lines
    PySpark
    bulk_approved = first_plan.approve_suggestions()
    individual_decisions = []
    for source_name, target_name in TRUTH["north"].items():
        if first_plan.result(source_name).approved_target is None:
            first_plan.approve(source_name, target_name, accept_semantic_risk=True, note="Reviewed against this synthetic lab fixture")
            individual_decisions.append((source_name, target_name))
    approved_mapping = first_plan.finalize()
    assert len(approved_mapping.renames) == len(TARGET.names)
    print(f"Bulk-approved suggestions: {len(bulk_approved)}")
    print(f"Individual reviewed decisions: {len(individual_decisions)}")
    print("Finalized mappings: " + ", ".join(f"{source} -> {target}" for source, target in approved_mapping.renames.items()))

    Output

    Bulk-approved suggestions: 5
    Individual reviewed decisions: 0
    Finalized mappings: TxnID -> transaction_id, TxnDate -> transaction_date, CustomerID -> customer_id, GrossAmount -> gross_amount, Currency -> currency
  6. Cell 6MarkdownExercise 3 — Apply the approved mapping with pandas
    Exercise 3 — Apply the approved mapping with pandas

    This small synthetic fixture is converted to pandas for the adapter exercise. Compare the exact rows and canonical column order with the authored reference mapping.

  7. Cell 7PySparkCode7 lines
    PySpark
    pandas_result = pandas_apply(north, approved_mapping, unmapped="drop", order="target")
    expected_north = north.rename(columns=TRUTH["north"])[list(TARGET.names)]
    assert pandas_result.equals(expected_north)
    print("pandas columns:", list(pandas_result.columns))
    print("pandas rows:")
    for row in pandas_result.to_dict(orient="records"):
        print(row)

    Output

    pandas columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
    pandas rows:
    {'transaction_id': 'N-1001', 'transaction_date': '2026-01-02', 'customer_id': 'C-20', 'gross_amount': '18.50', 'currency': 'USD'}
    {'transaction_id': 'N-1002', 'transaction_date': '2026-01-03', 'customer_id': 'C-21', 'gross_amount': '42.00', 'currency': 'USD'}
  8. Cell 8MarkdownExercise 4 — Apply the same approved mapping with Fabric Spark
    Exercise 4 — Apply the same approved mapping with Fabric Spark

    Fabric provides spark; this cell reuses it and does not create or stop a second session. Only the two-row fixture is collected for a parity assertion. The adapter itself creates a lazy projection; avoid collecting production-sized data to the driver.

  9. Cell 9PySparkCode7 lines
    PySpark
    from javimapper.adapters.spark import apply_mapping as spark_apply
    
    north_spark = spark.read.option("header", True).option("inferSchema", False).csv(f"{DATA_DIR}/north.csv")
    spark_result = spark_apply(north_spark, approved_mapping, unmapped="drop", order="target").toPandas()
    assert spark_result.equals(pandas_result)
    print("PySpark columns:", list(spark_result.columns))
    print(f"PySpark rows match pandas: {len(spark_result)}")

    Output

    PySpark columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
    PySpark rows match pandas: 2
  10. Cell 10MarkdownExercise 5: Reuse reviewed aliases across all three schemas
    Exercise 5: Reuse reviewed aliases across all three schemas

    An alias records a name relationship reviewed by a person; it is a useful starting point for later deliveries, not proof that the business meaning is the same. First compare the safe, no-alias proposals with proposals after alias reuse. In this synthetic fixture, RefNo stays unmatched because JaviMapper flags a semantic conflict: both names identify something, but one is a reference and the other a transaction. A reference number could identify many different things, so a person must resolve it explicitly.

    The scores are heuristic name-similarity rankings. They are not probabilities, confidence guarantees, or evidence of verified business meaning. ?Approved? means accepted by the safe bulk rule or explicitly reviewed here; ?Suggested? remains unapplied; ?Needs Review? is ambiguous or risky; ?Rejected? means a reviewer declined it; and ?Unmatched? means no supported suggestion was made. Even a clean run on these two-row fictional files does not establish production accuracy.

  11. Cell 11PySparkCompare how many decisions remain after safe bulk approval, with and without aliases35 lines
    PySpark
    # Compare how many decisions remain after safe bulk approval, with and without aliases.
    no_alias_suggestions = 0
    no_alias_manual_decisions = 0
    initial_report_html = None
    for merchant in TRUTH:
        frame = read_source(merchant)
        proposal = Matcher().suggest(schema_from_pandas(frame), TARGET)
        no_alias_suggestions += sum(result.suggested_target is not None for result in proposal.results)
        if merchant == "east":
            initial_report_html = render_html(proposal, title="East Market initial proposals (unapproved)")
        proposal.approve_suggestions()
        no_alias_manual_decisions += sum(result.approved_target is None for result in proposal.results)
    
    alias_plans = {}
    alias_suggestions = 0
    alias_manual_decisions = 0
    for merchant, expected in TRUTH.items():
        frame = read_source(merchant)
        plan = Matcher(MatchConfig(aliases=ALIASES)).suggest(schema_from_pandas(frame), TARGET)
        alias_plans[merchant] = plan
        alias_suggestions += sum(result.suggested_target is not None for result in plan.results)
        plan.approve_suggestions()
        alias_manual_decisions += sum(result.approved_target is None for result in plan.results)
        for source_name, target_name in expected.items():
            if plan.result(source_name).approved_target is None:
                plan.approve(source_name, target_name, accept_semantic_risk=True, note="Reviewed against this synthetic lab fixture")
        mapping = plan.finalize()
        actual = pandas_apply(frame, mapping, unmapped="drop", order="target")
        expected_frame = frame.rename(columns=expected)[list(TARGET.names)]
        assert actual.equals(expected_frame), merchant
        print(f"{merchant}: {sum(result.suggested_target is not None for result in plan.results)}/5 suggested; approved output matches the fixture")
    
    print(f"Without aliases: {no_alias_suggestions}/15 suggested; {no_alias_manual_decisions} rows remained for a human decision after safe bulk approval.")
    print(f"With reviewed aliases: {alias_suggestions}/15 suggested; {alias_manual_decisions} rows remained for a human decision after safe bulk approval.")
    print("These are counts from the supplied synthetic fixture; no review time was measured.")

    Output

    north: 5/5 suggested; approved output matches the fixture
    south: 3/5 suggested; approved output matches the fixture
    east: 4/5 suggested; approved output matches the fixture
    Without aliases: 9/15 suggested; 8 rows remained for a human decision after safe bulk approval.
    With reviewed aliases: 12/15 suggested; 3 rows remained for a human decision after safe bulk approval.
    These are counts from the supplied synthetic fixture; no review time was measured.
  12. Cell 12MarkdownExercise 6: Generate and display the HTML review reports
    Exercise 6: Generate and display the HTML review reports

    The first report below is the East Market proposal before approval. The second is the final reviewed plan, including the explicit RefNo decision and its note. The report summarizes mapping decisions and review rationale; it does not validate business meaning or prove production accuracy. The alias comparison above records only how many rows remained for a human decision on these fixtures. It does not estimate time saved.

    The notebook saves the final standalone report to Files/javimapper/output/mapping-report.html in Fabric (or output/mapping-report.html locally). It displays the same in-memory HTML, without rereading the saved file. If inline HTML is unavailable in the notebook, use the saved file in Lakehouse Explorer. Reports use the library's read-only HTML output and do not load external resources or scripts.

  13. Cell 13PySparkCode42 lines
    PySpark
    report_html = render_html(alias_plans["east"], title="JaviMapper synthetic merchant schema: reviewed decisions")
    if EXECUTION_MODE == "fabric":
        report_dir = "Files/javimapper/output"
        notebookutils.fs.mkdirs(report_dir)
        report_path = f"{report_dir}/mapping-report.html"
        notebookutils.fs.put(report_path, report_html, True)
        print(f"HTML report generated in the default Lakehouse: {report_path} ({len(report_html.encode('utf-8'))} bytes)")
    else:
        output_dir = LAB_ROOT / "output"
        output_dir.mkdir(exist_ok=True)
        report_path = output_dir / "mapping-report.html"
        report_path.write_text(report_html, encoding="utf-8")
        print(f"HTML report generated locally: output/{report_path.name} ({report_path.stat().st_size} bytes)")
    
    report_display_path = report_path if EXECUTION_MODE == "fabric" else "output/mapping-report.html"
    
    inline_displayed = False
    display_error = None
    try:
        from IPython.display import HTML, display
        print("Inline reports: initial unapproved proposals, then reviewed decisions")
        display(HTML(initial_report_html))
        display(HTML(report_html))
        inline_displayed = True
    except Exception as exc:
        display_error = exc
    
    # Some Fabric notebook kernels expose displayHTML even when IPython MIME display is absent.
    if not inline_displayed and EXECUTION_MODE == "fabric" and callable(globals().get("displayHTML")):
        try:
            displayHTML(initial_report_html)
            displayHTML(report_html)
            inline_displayed = True
        except Exception as exc:
            display_error = exc
    
    if inline_displayed:
        print("Inline HTML display submitted; confirm rendering in the target Fabric notebook.")
    else:
        print(f"Inline HTML display unavailable; open the saved report at {report_display_path}.")
        if display_error is not None:
            print(f"Display fallback: {type(display_error).__name__}")

    Output

    HTML report generated locally: output/mapping-report.html (18189 bytes)
    Inline HTML display unavailable; open the saved report at output/mapping-report.html.
    Display fallback: ModuleNotFoundError
  14. Cell 14MarkdownReview the reports and compare decisions
    Review the reports and compare decisions

    Compare the initial East Market proposals with the final reviewed report. The RefNo mapping appears only after an explicit human decision because a reference identifier is not automatically the same business concept as a transaction identifier. Approved aliases can make later schemas easier to review, while every new dataset still needs business validation.

    On the supplied synthetic fixture, the no-alias proposals produced 9 of 15 suggestions and left 8 rows for a human decision after safe bulk approval; reviewed-alias proposals produced 12 of 15 suggestions and left 3 rows. These counts are locally observed fixture results, not measured time savings or a prediction of production accuracy. The saved outputs in this notebook are local; inline HTML rendering and file access still need confirmation in a live Fabric workspace.

Review results

Compare the initial proposal report with the final reviewed report. Approved mappings were accepted by a safe bulk rule or explicitly reviewed; suggestions remain unapplied, Needs Review signals ambiguity or risk, Rejected records a reviewer’s decision, and Unmatched means no supported proposal was made. Heuristic scores rank name similarity; they are not probabilities or verified business meaning. RefNo requires explicit review because a reference identifier may describe a different business object than a transaction identifier. On this synthetic fixture, the no-alias proposals yielded 9/15 suggestions and 8 rows for human decisions after safe bulk approval; reviewed aliases yielded 12/15 and 3. These are fixture counts, not measured time savings or evidence of production accuracy. The final report is saved to Files/javimapper/output/mapping-report.html.

Using JaviMapper in a real Fabric pipeline

The next two notebooks reuse the same published Fabric Environment and one JaviMapper 0.6.0b1 wheel. Attach that Environment and the same default Lakehouse to both notebooks. Upload east.csv and east_delivery_02.csv to Files/javimapper/input/. The onboarding notebook shows the proposal and records educational reference decisions for this fictional file; those scripted decisions are not an interactive approval by a data owner.

Merchant onboarding

Review the first report, inspect semantic warnings, and make explicit decisions. The notebook saves Files/javimapper/config/east-market/approved-mapping-v1.json. This approved mapping JSON is the validated source schema, target schema, and approved source-to-target contract used by ingestion. The optional east-market-aliases-v1.json is a different file: it contains reviewed hints for future matching. It does not replace the approved mapping and is not used by recurring ingestion. Versioned files are create-only; choose a new version name instead of overwriting an existing approval.

Notebook: merchant-onboarding.ipynb

PySpark notebook10 cells

Read-only view of the notebook file. Nothing on this page runs code.

  1. Cell 1MarkdownMerchant onboarding with JaviMapper

    Merchant onboarding with JaviMapper

    This Fabric Spark notebook demonstrates how a team can review a new merchant schema once and save an approved mapping for later ingestion. It uses only fictional East Market data. It does not create or modify Fabric items automatically.

    Attach the same published Environment that contains the private javimapper==0.6.0b1 wheel and attach the lab Lakehouse as the default Lakehouse. Upload east.csv and east_delivery_02.csv from labs/javimapper-mapping-lab/data/ to Files/javimapper/input/. The approved mapping is written to Files/javimapper/config/east-market/approved-mapping-v1.json; an optional alias export is a separate file.

    Approval note: the decisions in this notebook are scripted educational reference decisions for the fictional fixture. They are not an interactive approval by a data owner. In a real onboarding workflow, stop after reviewing the proposal and have an authorized person approve the decisions before saving them.

  2. Cell 2Markdown1. Verify the Environment and source file
    1. Verify the Environment and source file

    Fabric supplies the running spark session. The notebook does not install packages or start another Fabric session. In local mode, it uses a local Spark session only when one was not supplied.

  3. Cell 3PySparkCode49 lines
    PySpark
    from datetime import date
    from pathlib import Path
    import sys
    import pyspark
    import javimapper
    from javimapper import AliasSet, Field, MatchMethod, Matcher, Schema, render_html
    from javimapper.adapters.spark import schema_from_spark
    
    EXECUTION_MODE = "fabric"  # set to "local" only for local notebook testing
    EXPECTED_VERSION = "0.6.0b1"
    assert javimapper.__version__ == EXPECTED_VERSION, f"Expected {EXPECTED_VERSION}; found {javimapper.__version__}"
    
    if EXECUTION_MODE == "fabric":
        assert "spark" in globals(), "Use a Fabric Spark notebook with its provided spark session."
        assert "notebookutils" in globals(), "Attach the default Lakehouse in Fabric."
        INPUT_DIR = "Files/javimapper/input"
        CONFIG_DIR = "Files/javimapper/config/east-market"
        OUTPUT_DIR = "Files/javimapper/output"
        required_files = {"east.csv", "east_delivery_02.csv"}
        found_files = {item.name for item in notebookutils.fs.ls(INPUT_DIR) if item.isFile}
        assert required_files <= found_files, f"Missing Lakehouse files: {sorted(required_files - found_files)}"
        SOURCE_PATH = f"{INPUT_DIR}/east.csv"
    else:
        from pyspark.sql import SparkSession
        LOCAL_LAKEHOUSE_ROOT = Path(globals().get("LOCAL_LAKEHOUSE_ROOT", Path.cwd() / ".codex-artifacts/javimapper-local-lakehouse")).resolve()
        if "spark" not in globals():
            spark = SparkSession.builder.master("local[1]").appName("JaviMapperOnboardingLab").getOrCreate()
        local_input = LOCAL_LAKEHOUSE_ROOT / "Files/javimapper/input"
        required_files = {"east.csv", "east_delivery_02.csv"}
        found_files = {p.name for p in local_input.glob("*.csv")}
        assert required_files <= found_files, f"Copy both synthetic East Market CSVs to {local_input}"
        INPUT_DIR = str(local_input)
        CONFIG_DIR = LOCAL_LAKEHOUSE_ROOT / "Files/javimapper/config/east-market"
        OUTPUT_DIR = LOCAL_LAKEHOUSE_ROOT / "Files/javimapper/output"
        SOURCE_PATH = str(local_input / "east.csv")
    
    print(f"JaviMapper {javimapper.__version__} | Python {sys.version.split()[0]} | PySpark {pyspark.__version__} | Spark {spark.version}")
    print(f"Source file: {Path(SOURCE_PATH).name} (fictional East Market data)")
    source_df = spark.read.option("header", True).option("inferSchema", False).csv(SOURCE_PATH)
    source_schema = schema_from_spark(source_df)
    TARGET_SCHEMA = Schema.of([
        Field("transaction_id", "string", required=True),
        Field("transaction_date", "string", required=True),
        Field("customer_id", "string", required=True),
        Field("gross_amount", "string", required=True),
        Field("currency", "string", required=True),
    ])
    print("Source columns and Spark types:", [(field.name, field.dtype) for field in source_schema])
    print("Required canonical fields:", TARGET_SCHEMA.names)

    Output

    JaviMapper 0.6.0b1 | Python 3.12.10 | PySpark 4.3.0 | Spark 4.3.0
    Source file: east.csv (fictional East Market data)
    Source columns and Spark types: [('RefNo', 'string'), ('DateOfSale', 'string'), ('ClientNo', 'string'), ('SaleValue', 'string'), ('Currency', 'string')]
    Required canonical fields: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
  4. Cell 4Markdown2. Inspect the initial proposal
    2. Inspect the initial proposal

    The report is a read-only summary of suggestions, warnings and alternatives. It does not inspect row values or decide whether two names have the same business meaning. In particular, RefNo is not automatically treated as a transaction identifier: the semantic safeguard sees a reference-versus-transaction conflict.

  5. Cell 5PySparkCode19 lines
    PySpark
    plan = Matcher().suggest(source_schema, TARGET_SCHEMA)
    print(plan.explain())
    for result in plan.results:
        for warning in result.warnings:
            print(f"Review warning for {result.source}: {warning.message}")
    refno_risks = plan.semantic_risks("RefNo", "transaction_id", MatchMethod.MANUAL)
    for risk in refno_risks:
        print(f"RefNo semantic warning ({risk.kind.value}): {risk.message}")
    
    initial_report_html = render_html(plan, title="East Market onboarding: initial unapproved proposals")
    print("Initial proposal HTML prepared from memory.")
    try:
        from IPython.display import HTML, display
        display(HTML(initial_report_html))
    except Exception as display_error:
        if EXECUTION_MODE == "fabric" and callable(globals().get("displayHTML")):
            displayHTML(initial_report_html)
        else:
            print(f"Inline HTML display unavailable ({type(display_error).__name__}); the report remains available in this cell's code-generated preview only.")

    Output

    source      suggested target  method      score   state         notes
    ----------  ----------------  ----------  ------  ------------  -----
    RefNo       -                 -           -       unmatched
    DateOfSale  -                 -           -       unmatched
    ClientNo    customer_id       fuzzy       0.7324  needs_review  fuzzy_match; semantic_risk
    SaleValue   -                 -           -       unmatched
    Currency    currency          normalized  1.0000  suggested
    
    [conflict] required target 'transaction_id' has no suggested source
    [conflict] required target 'transaction_date' has no suggested source
    [conflict] required target 'gross_amount' has no suggested source
    
    Scores are heuristic name-similarity scores, not probabilities.
    Review warning for RefNo: no target candidate for 'RefNo'
    Review warning for DateOfSale: no target candidate for 'DateOfSale'
    Review warning for ClientNo: 'ClientNo' -> 'customer_id' is a fuzzy suggestion (heuristic score 0.7324); review it
    Review warning for ClientNo: 'ClientNo' has ['number'] and 'customer_id' has ['identifier'], which the other lacks
    Review warning for SaleValue: no target candidate for 'SaleValue'
    RefNo semantic warning (role_conflict): both are 'identifier' columns, but of different things: 'reference' vs 'transaction'
    Initial proposal HTML prepared from memory.
    Inline HTML display unavailable (ModuleNotFoundError); the report remains available in this cell's code-generated preview only.
  6. Cell 6Markdown3. Review and explicitly approve the educational example
    3. Review and explicitly approve the educational example

    The following decisions describe this synthetic reference file only. The code makes the approvals explicit so the saved JSON records the chosen source-to-target pairs and the RefNo semantic-risk override. A production process should collect approval from an authorized person and record a real reviewer identity or ticket.

  7. Cell 7PySparkScripted teaching example only; this is not a live human approval workflow38 lines
    PySpark
    # Scripted teaching example only; this is not a live human approval workflow.
    approved_safe = plan.approve_suggestions()
    EDUCATIONAL_REFERENCE = {
        "RefNo": "transaction_id",
        "DateOfSale": "transaction_date",
        "ClientNo": "customer_id",
        "SaleValue": "gross_amount",
        "Currency": "currency",
    }
    for source_name, target_name in EDUCATIONAL_REFERENCE.items():
        if plan.result(source_name).approved_target is None:
            if source_name == "RefNo":
                plan.approve(
                    source_name, target_name, accept_semantic_risk=True,
                    note="EDUCATIONAL REFERENCE ONLY: confirm this business meaning with an authorized data owner before use.",
                    approved_by="synthetic lab example; no human approval recorded",
                )
            else:
                plan.approve(
                    source_name, target_name,
                    note="EDUCATIONAL REFERENCE ONLY: mapping checked against the fictional fixture.",
                    approved_by="synthetic lab example; no human approval recorded",
                )
    assert not plan.missing_required(), f"Required fields still need decisions: {plan.missing_required()}"
    approved_mapping = plan.finalize(description="East Market fictional onboarding reference; version 1")
    assert approved_mapping.missing_required == []
    print(f"Clean suggestions approved by the safe rule: {len(approved_safe)}")
    print("Final reference mapping:", approved_mapping.renames)
    print("Required fields mapped:", approved_mapping.target_schema.names)
    approved_report_html = render_html(plan, title="East Market onboarding: educational approved reference")
    try:
        from IPython.display import HTML, display
        display(HTML(approved_report_html))
    except Exception as display_error:
        if EXECUTION_MODE == "fabric" and callable(globals().get("displayHTML")):
            displayHTML(approved_report_html)
        else:
            print(f"Inline HTML display unavailable ({type(display_error).__name__}); approved report HTML was generated.")

    Output

    Clean suggestions approved by the safe rule: 1
    Final reference mapping: {'RefNo': 'transaction_id', 'DateOfSale': 'transaction_date', 'ClientNo': 'customer_id', 'SaleValue': 'gross_amount', 'Currency': 'currency'}
    Required fields mapped: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
    Inline HTML display unavailable (ModuleNotFoundError); approved report HTML was generated.
  8. Cell 8Markdown4. Save a versioned approved mapping and optional aliases
    4. Save a versioned approved mapping and optional aliases

    Approved mapping JSON is the complete, validated contract Notebook 2 needs: source schema metadata, target schema metadata, approved source-to-target pairs, methods, notes and any accepted safeguards. The alias JSON is a separate optional matching aid for future onboarding. Aliases do not replace the approved mapping and are not proof that future data has the same meaning.

    Version 1 is create-only. If the file already exists, do not overwrite it; review the change and deliberately choose a new versioned filename.

  9. Cell 9PySparkCode34 lines
    PySpark
    MAPPING_FILENAME = "approved-mapping-v1.json"
    ALIAS_FILENAME = "east-market-aliases-v1.json"
    mapping_json = approved_mapping.to_json()
    alias_set = AliasSet.from_mapping(
        approved_mapping,
        namespace="east-market",
        description="Optional reviewed hints exported from the fictional onboarding reference.",
        reviewed_at=date.today().isoformat(),
    )
    alias_json = alias_set.to_json()
    
    if EXECUTION_MODE == "fabric":
        notebookutils.fs.mkdirs(CONFIG_DIR)
        notebookutils.fs.put(f"{CONFIG_DIR}/{MAPPING_FILENAME}", mapping_json, False)
        notebookutils.fs.put(f"{CONFIG_DIR}/{ALIAS_FILENAME}", alias_json, False)
        notebookutils.fs.mkdirs(OUTPUT_DIR)
        notebookutils.fs.put(f"{OUTPUT_DIR}/east-market-approved-v1.html", approved_report_html, False)
        print(f"Created {CONFIG_DIR}/{MAPPING_FILENAME}")
        print(f"Created optional alias set {CONFIG_DIR}/{ALIAS_FILENAME}")
    else:
        CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        for path, content in (
            (CONFIG_DIR / MAPPING_FILENAME, mapping_json),
            (CONFIG_DIR / ALIAS_FILENAME, alias_json),
            (OUTPUT_DIR / "east-market-approved-v1.html", approved_report_html),
        ):
            if path.exists():
                raise FileExistsError(f"Refusing to overwrite versioned lab artifact: {path.name}; choose a new version.")
            path.write_text(content, encoding="utf-8")
        print(f"Created Files/javimapper/config/east-market/{MAPPING_FILENAME}")
        print(f"Created optional alias set Files/javimapper/config/east-market/{ALIAS_FILENAME}")
    print(f"Approved mapping format: {approved_mapping.to_dict()['format']} v{approved_mapping.to_dict()['format_version']}")
    print(f"Optional alias format: {alias_set.to_dict()['format']} v{alias_set.to_dict()['format_version']}")

    Output

    Created Files/javimapper/config/east-market/approved-mapping-v1.json
    Created optional alias set Files/javimapper/config/east-market/east-market-aliases-v1.json
    Approved mapping format: javimapper.approved-mapping v1
    Optional alias format: javimapper.alias-set v2
  10. Cell 10MarkdownWhat this example does not approve
    What this example does not approve

    JaviMapper proposes names; it does not transform values, establish business semantics, or approve decisions on behalf of a person. An unsupported or ambiguous field must remain unresolved until reviewed. This example's explicit RefNo override exists only to exercise the audit trail on fictional data. Do not copy it into a production mapping without independent approval.

Recurring ingestion

The second notebook starts in a fresh Python namespace and loads the saved mapping JSON directly from OneLake. It does not import onboarding variables or run fuzzy matching. It checks the incoming source names, order, Spark types, required output fields and duplicate keys before writing. A mismatch stops processing for review.

JaviMapper standardizes the approved source columns into canonical columns. The notebook—not JaviMapper—adds merchant, file, delivery and ingestion-time metadata, defines the (source_merchant, transaction_id) key, checks duplicates, creates the lab-specific javimapper_lab_standardized_transactions Delta table, and runs Delta MERGE. Captured Fabric results: first run input=2, inserted=2, matched/upserted=0, stored=2, duplicate keys=0; replay input=2, inserted=0, matched/upserted=2, stored=2, duplicate keys=0. The replay updated ingested_at_utc, so duplicate-free idempotency does not mean byte-identical rows. This lab table is separate from business tables.

Notebook: recurring-ingestion.ipynb

PySpark notebook10 cells

Read-only view of the notebook file. Nothing on this page runs code.

  1. Cell 1MarkdownRecurring ingestion with an approved JaviMapper contract

    Recurring ingestion with an approved JaviMapper contract

    This notebook is intentionally independent from the onboarding notebook's Python variables. It loads the saved ApprovedMapping JSON from the default Lakehouse, checks the second fictional East Market delivery against the stored source schema, applies only that approved mapping with PySpark, and upserts the standardized rows into a lab-specific Delta table.

    Attach the same published Environment containing javimapper==0.6.0b1 and the same default Lakehouse. Notebook 1 must have created Files/javimapper/config/east-market/approved-mapping-v1.json. Upload east_delivery_02.csv to Files/javimapper/input/. This notebook never invokes Matcher, runs fuzzy matching, or approves a new mapping.

  2. Cell 2Markdown1. Verify the Environment and load saved configuration
    1. Verify the Environment and load saved configuration

    The approved mapping JSON is authoritative for this ingestion run. The optional alias JSON is only a future matching aid and is not loaded here.

  3. Cell 3PySparkCode35 lines
    PySpark
    from pathlib import Path
    import sys
    import pyspark
    import javimapper
    from javimapper import ApprovedMapping
    from javimapper.adapters.spark import apply_mapping, schema_from_spark
    
    EXECUTION_MODE = "fabric"  # set to "local" only for local notebook testing
    EXPECTED_VERSION = "0.6.0b1"
    assert javimapper.__version__ == EXPECTED_VERSION, f"Expected {EXPECTED_VERSION}; found {javimapper.__version__}"
    TABLE_NAME = "javimapper_lab_standardized_transactions"
    MAPPING_RELATIVE = "Files/javimapper/config/east-market/approved-mapping-v1.json"
    SOURCE_RELATIVE = "Files/javimapper/input/east_delivery_02.csv"
    
    if EXECUTION_MODE == "fabric":
        assert "spark" in globals(), "Use the Fabric-provided Spark session."
        assert "notebookutils" in globals(), "Attach the default Lakehouse in Fabric."
        mapping_json = notebookutils.fs.head(MAPPING_RELATIVE, 1_000_000)
        SOURCE_PATH = SOURCE_RELATIVE
    else:
        from pyspark.sql import SparkSession
        LOCAL_LAKEHOUSE_ROOT = Path(globals().get("LOCAL_LAKEHOUSE_ROOT", Path.cwd() / ".codex-artifacts/javimapper-local-lakehouse")).resolve()
        if "spark" not in globals():
            spark = SparkSession.builder.master("local[1]").appName("JaviMapperRecurringIngestionLab").getOrCreate()
        mapping_path = LOCAL_LAKEHOUSE_ROOT / MAPPING_RELATIVE
        mapping_json = mapping_path.read_text(encoding="utf-8")
        SOURCE_PATH = str(LOCAL_LAKEHOUSE_ROOT / SOURCE_RELATIVE)
        LOCAL_TABLE_PATH = LOCAL_LAKEHOUSE_ROOT / "Tables" / f"{TABLE_NAME}.json"
    
    mapping = ApprovedMapping.from_json(mapping_json)
    assert mapping.target_schema.names == ["transaction_id", "transaction_date", "customer_id", "gross_amount", "currency"]
    assert not mapping.missing_required, f"Mapping does not cover required fields: {mapping.missing_required}"
    print(f"JaviMapper {javimapper.__version__} | Python {sys.version.split()[0]} | PySpark {pyspark.__version__} | Spark {spark.version}")
    print(f"Loaded approved mapping JSON: {MAPPING_RELATIVE}")
    print(f"Approved source columns: {mapping.source_schema.names}")

    Output

    JaviMapper 0.6.0b1 | Python 3.12.10 | PySpark 4.3.0 | Spark 4.3.0
    Loaded approved mapping JSON: Files/javimapper/config/east-market/approved-mapping-v1.json
    Approved source columns: ['RefNo', 'DateOfSale', 'ClientNo', 'SaleValue', 'Currency']
  4. Cell 4Markdown2. Stop on source schema drift
    2. Stop on source schema drift

    The expected source names, order and Spark type metadata come from the saved mapping file. Any missing, unexpected, reordered or type-changed column stops the notebook before applying the mapping. Resolve a real schema change in onboarding; do not guess a new match during recurring ingestion.

  5. Cell 5PySparkCode13 lines
    PySpark
    source_df = spark.read.option("header", True).option("inferSchema", False).csv(SOURCE_PATH)
    current_source_schema = schema_from_spark(source_df)
    expected_source_columns = mapping.source_schema.names
    actual_source_columns = current_source_schema.names
    missing_columns = sorted(set(expected_source_columns) - set(actual_source_columns))
    unexpected_columns = sorted(set(actual_source_columns) - set(expected_source_columns))
    if missing_columns or unexpected_columns:
        raise ValueError(f"Source columns differ from approved mapping. Missing={missing_columns}; unexpected={unexpected_columns}")
    if current_source_schema != mapping.source_schema:
        raise ValueError(f"Source schema metadata or column order changed. Expected={mapping.source_schema.to_dict()}; actual={current_source_schema.to_dict()}")
    mapping.check_columns(actual_source_columns, keep_unmapped=False)
    print("Source columns and Spark type metadata match the approved onboarding schema.")
    print(f"Input: {Path(SOURCE_PATH).name}; columns={actual_source_columns}")

    Output

    Source columns and Spark type metadata match the approved onboarding schema.
    Input: east_delivery_02.csv; columns=['RefNo', 'DateOfSale', 'ClientNo', 'SaleValue', 'Currency']
  6. Cell 6Markdown3. Apply only the approved mapping and validate output
    3. Apply only the approved mapping and validate output

    JaviMapper renames and orders columns; it does not cast values. This fixture keeps source and canonical values as strings. Production pipelines should define and test any required type conversions separately.

  7. Cell 7PySparkCode31 lines
    PySpark
    from pyspark.sql import functions as F
    
    SOURCE_MERCHANT = "east_market"
    SOURCE_FILE = "east_delivery_02.csv"
    DELIVERY_ID = "east_market_delivery_02"
    canonical_columns = mapping.target_schema.names
    required_columns = [field.name for field in mapping.target_schema if field.required]
    standardized = apply_mapping(source_df, mapping, unmapped="drop", order="target")
    if standardized.columns != canonical_columns:
        raise ValueError(f"Canonical output columns differ: {standardized.columns}")
    missing_required = sorted(set(required_columns) - set(standardized.columns))
    if missing_required:
        raise ValueError(f"Required canonical columns are absent: {missing_required}")
    null_required = [name for name in required_columns if standardized.filter(F.col(name).isNull()).limit(1).count()]
    if null_required:
        raise ValueError(f"Required canonical columns contain nulls: {null_required}")
    
    # Pipeline metadata is added after JaviMapper; it is not part of the mapping contract.
    incoming = (standardized
        .withColumn("source_merchant", F.lit(SOURCE_MERCHANT))
        .withColumn("source_file", F.lit(SOURCE_FILE))
        .withColumn("delivery_id", F.lit(DELIVERY_ID))
        .withColumn("ingested_at_utc", F.current_timestamp()))
    key_columns = ["source_merchant", "transaction_id"]
    duplicate_input_keys = (incoming.groupBy(*key_columns).count().filter(F.col("count") > 1).limit(1).count())
    if duplicate_input_keys:
        raise ValueError(f"Delivery contains duplicate upsert keys: {key_columns}")
    input_rows = incoming.count()
    print(f"Canonical output columns: {canonical_columns}")
    print(f"Required fields present and non-null: {required_columns}")
    print(f"Input rows ready for idempotent upsert: {input_rows}")

    Output

    Canonical output columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
    Required fields present and non-null: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
    Input rows ready for idempotent upsert: 2
  8. Cell 8Markdown4. Upsert into the lab-specific Delta table
    4. Upsert into the lab-specific Delta table

    Fabric writes to the dedicated table javimapper_lab_standardized_transactions. First creation fails if that table already exists; later runs use Delta MERGE keyed by (source_merchant, transaction_id). A repeated delivery updates the existing key rather than inserting a duplicate. This notebook never overwrites another table.

    For local testing only, the notebook uses a dedicated JSON file because the repository's local Spark environment does not include Fabric's Delta runtime and may lack Windows Hadoop helpers. It applies the same key-based replacement logic to the tiny fixture; this is not evidence of a live Fabric Delta write.

  9. Cell 9PySparkCode73 lines
    PySpark
    import json
    from datetime import date, datetime
    
    if EXECUTION_MODE == "fabric":
        from delta.tables import DeltaTable
        table_exists = spark.catalog.tableExists(TABLE_NAME)
        if table_exists:
            existing = spark.table(TABLE_NAME)
            existing_types = [(field.name, field.dataType.simpleString()) for field in existing.schema.fields]
            incoming_types = [(field.name, field.dataType.simpleString()) for field in incoming.schema.fields]
            if existing_types != incoming_types:
                raise ValueError(f"Existing lab Delta table schema changed. Existing={existing_types}; incoming={incoming_types}")
            existing_keys = existing.select(*key_columns).distinct()
            inserted_rows = incoming.select(*key_columns).join(existing_keys, key_columns, "left_anti").count()
            matched_rows = input_rows - inserted_rows
            condition = " AND ".join(f"target.{name} = source.{name}" for name in key_columns)
            (DeltaTable.forName(spark, TABLE_NAME).alias("target")
                .merge(incoming.alias("source"), condition)
                .whenMatchedUpdateAll()
                .whenNotMatchedInsertAll()
                .execute())
        else:
            inserted_rows = input_rows
            matched_rows = 0
            incoming.write.format("delta").mode("errorifexists").saveAsTable(TABLE_NAME)
        stored = spark.table(TABLE_NAME)
        stored_rows = stored.count()
        stored_duplicates = stored.groupBy(*key_columns).count().filter(F.col("count") > 1).limit(1).count()
        current_delivery_rows = stored.filter(F.col("delivery_id") == DELIVERY_ID).count()
        stored.orderBy("transaction_id").show(truncate=False)
        storage_format = "Fabric Delta"
    else:
        # The local Spark test environment has no Delta runtime and may lack winutils; persist only the
        # tiny fictional fixture with standard Python JSON I/O after Spark has transformed it.
        LOCAL_TABLE_PATH.parent.mkdir(parents=True, exist_ok=True)
        schema_signature = [[field.name, field.dataType.simpleString()] for field in incoming.schema.fields]
        if LOCAL_TABLE_PATH.exists():
            local_state = json.loads(LOCAL_TABLE_PATH.read_text(encoding="utf-8"))
            if local_state.get("schema") != schema_signature:
                raise ValueError("Existing local lab table schema differs; refusing to replace it.")
            stored_records = local_state["rows"]
        else:
            stored_records = []
        incoming_records = []
        for row in incoming.collect():
            record = row.asDict(recursive=True)
            if isinstance(record.get("ingested_at_utc"), datetime):
                record["ingested_at_utc"] = record["ingested_at_utc"].isoformat() + "Z"
            incoming_records.append(record)
        existing_keys = {(row["source_merchant"], row["transaction_id"]) for row in stored_records}
        incoming_keys = [(row["source_merchant"], row["transaction_id"]) for row in incoming_records]
        incoming_key_set = set(incoming_keys)
        inserted_rows = sum(key not in existing_keys for key in incoming_keys)
        matched_rows = input_rows - inserted_rows
        retained = [row for row in stored_records if (row["source_merchant"], row["transaction_id"]) not in incoming_key_set]
        merged_records = retained + incoming_records
        LOCAL_TABLE_PATH.write_text(json.dumps({"schema": schema_signature, "rows": merged_records}, indent=2, default=str) + "\n", encoding="utf-8")
        stored_records = merged_records
        stored_rows = len(stored_records)
        stored_keys = [(row["source_merchant"], row["transaction_id"]) for row in stored_records]
        stored_duplicates = int(len(stored_keys) != len(set(stored_keys)))
        current_delivery_rows = sum(row["delivery_id"] == DELIVERY_ID for row in stored_records)
        print(json.dumps(sorted(stored_records, key=lambda row: row["transaction_id"]), indent=2))
        storage_format = "local JSON test fallback"
    
    if stored_duplicates:
        raise AssertionError("Upsert produced duplicate merchant transaction keys.")
    if current_delivery_rows != input_rows:
        raise AssertionError(f"Expected {input_rows} rows for this delivery; found {current_delivery_rows}.")
    assert inserted_rows + matched_rows == input_rows
    print(f"Storage: {storage_format} | table: {TABLE_NAME}")
    print(f"Reconciliation: input={input_rows}, inserted={inserted_rows}, matched/upserted={matched_rows}, stored={stored_rows}, delivery_rows={current_delivery_rows}")
    print("Duplicate upsert keys in stored table: 0")

    Output

    [
      {
        "transaction_id": "E-3003",
        "transaction_date": "2026-03-08",
        "customer_id": "C-42",
        "gross_amount": "19.95",
        "currency": "GBP",
        "source_merchant": "east_market",
        "source_file": "east_delivery_02.csv",
        "delivery_id": "east_market_delivery_02",
        "ingested_at_utc": "2026-11-29T17:13:31.922159Z"
      },
      {
        "transaction_id": "E-3004",
        "transaction_date": "2026-03-09",
        "customer_id": "C-43",
        "gross_amount": "72.10",
        "currency": "GBP",
        "source_merchant": "east_market",
        "source_file": "east_delivery_02.csv",
        "delivery_id": "east_market_delivery_02",
        "ingested_at_utc": "2026-11-29T17:13:31.922159Z"
      }
    ]
    Storage: local JSON test fallback | table: javimapper_lab_standardized_transactions
    Reconciliation: input=2, inserted=2, matched/upserted=0, stored=2, delivery_rows=2
    Duplicate upsert keys in stored table: 0
  10. Cell 10MarkdownRerun and failure behavior
    Rerun and failure behavior

    Run this notebook again with the same delivery ID to exercise idempotency: the expected result is zero new inserts and two matched/upserted keys, with no duplicate (source_merchant, transaction_id) rows. Unexpected source columns, missing required fields, schema metadata changes and duplicate keys fail before the write. If an earlier write partially completes, rerunning the same delivery safely reconciles the same keys.

    A different file or source schema must go through onboarding first. Create a new approved mapping version there; never auto-match or auto-approve changes in this ingestion notebook.

The local execution tests use a small JSON persistence fallback because the local Spark environment does not include Fabric’s Delta runtime. Confirm the Delta table creation, MERGE behavior, OneLake paths and Environment compatibility in a live Fabric workspace before treating them as Fabric-validated.

Troubleshooting and cleanup

Stop the notebook session when finished. Remove the Environment, notebook or Lakehouse only if created solely for this lab and no longer needed; do not remove shared workspace resources.

Optional local pandas/PySpark path

From the repository root:

python -m pip install -e "./libraries/javimapper[pandas,spark]"
python labs/javimapper-mapping-lab/run_lab.py

Configure Java supported by PySpark. For the notebook, change EXECUTION_MODE to local; it finds the fixtures in the repository or extracted private lab bundle and creates a local Spark session only if none exists. The local script writes results under the lab’s output/ directory. The bundle and wheel remain private; neither is a website download.

Advanced: build the wheel from source

From the repository root, prepare a private local wheel when needed:

python -m pip install --upgrade build
python -m build --wheel --outdir .codex-artifacts/private-wheels libraries/javimapper
python -m zipfile -l .codex-artifacts/private-wheels/javimapper-0.6.0b1-py3-none-any.whl

Confirm the package version and Apache-2.0 LICENSE/NOTICE metadata. The wheel should contain no credentials, local data, virtual environments or machine-specific paths. Fabric supplies pandas and PySpark through its selected runtime; do not add optional wheels without checking compatibility. Keep the output under the ignored .codex-artifacts/ directory, never public/ or dist/.