Disponibilité des paquets : JaviMapper est une bêta non publiée et JaviPerf est expérimental. Aucun des deux n’est disponible sur PyPI ni sous forme de wheel public, et le dépôt du code source est privé. Les visiteurs ne peuvent pas obtenir ni compiler ces paquets depuis ce site. Les étapes d’installation dans Fabric nécessitent un wheel déjà autorisé et fourni en privé ; sans cet accès, les exercices ne peuvent pas être exécutés.

Atelier pratique : rapprocher trois schémas de commerçants

Microsoft Fabric est le parcours principal. Installez le wheel privé JaviMapper 0.6.0b1 dans un Environment dédié, associez un Lakehouse contenant trois CSV fictifs et exécutez les six exercices du notebook existant. Le parcours local reste disponible en option.

  1. Construire le wheel privé
  2. Publier l’Environment
  3. Associer notebook et Lakehouse
  4. Vérifier et appliquer les mappings
  5. Examiner le rapport et l’effort
Préparez un wheel privé et un Environment Fabric, puis exécutez des mappings vérifiés sur des fichiers Lakehouse synthétiques.

Prérequis

Consultez les versions et le cycle de vie actuels dans les runtimes Spark Fabric et Runtime 2.0.

Télécharger le wheel

Ouvrez Microsoft Fabric et créez un workspace et un Environment dédiés à l’atelier. Dans l’Environment, chargez le wheel téléchargé sous Custom libraries, enregistréz puis publiez. Associez l’Environment publié à ce notebook, démarrez une nouvelle session et vérifiez que import javimapper; print(javimapper.__version__) renvoie 0.6.0b1. Poursuivez avec la configuration ci-dessous. Le lien fonctionne uniquement sur le serveur local de développement JaviBuilds. Ce wheel privé n’est pas publié sur PyPI et ne doit pas être copié dans les ressources du site.

Créer un Environment Fabric

Dans le workspace dédié, sélectionnez + New → Environment, créez un élément réservé au laboratoire et ouvrez les paramètres Spark. Choisissez le runtime après avoir comparé ses versions Python, Spark, pandas et PySpark aux exigences. Le wheel Python pur évite les contraintes ABI des wheels compilés, mais l’adaptateur PySpark dépend toujours d’un runtime Spark/PySpark compatible.

Ne déduisez pas la compatibilité du nom du runtime. Si l’import ou les contrôles de l’adaptateur échouent, choisissez un runtime pris en charge ou demandez une version compatible de la bibliothèque. Ne forcez pas la mise à niveau de packages Spark gérés par Fabric avec %pip ou une surcharge de l’Environment sans test.

Charger et publier la bibliothèque

Dans Libraries de l’Environment, choisissez Custom libraries, téléversez le .whl local, enregistréz, puis sélectionnez Publish. Choisissez le mode de publication proposé ; Full crée un instantané stable et peut prendre plus de temps que Quick. Attendez la fin et confirmez l’état de la bibliothèque. Consultez la gestion des bibliothèques et la création et l’utilisation d’un Environment.

En cas de conflit de publication ou de dépendances, conservez l’erreur complète et comparez-la aux packages intégrés du runtime. Ne modifiez pas pandas ou PySpark à l’aveugle. Choisissez un runtime compatible ou une version de JaviMapper validée pour ce runtime.

Associer l’Environment

Créez ou ouvrez un notebook Spark Fabric, sélectionnez le nouvel Environment dans le sélecteur et confirmez. Démarrez une nouvelle session après l’association ou le changement ; une session ouverte ne l’adopte pas. Exécutez la première cellule pour vérifier javimapper.__version__ == "0.6.0b1" et afficher les versions Python, PySpark et Spark. Le notebook réutilise le spark fourni par Fabric.

Créer ou associer un Lakehouse

Créez un Lakehouse dédié ou associez-en un réservé au laboratoire et définissez-le comme Lakehouse par défaut du notebook. Dans Lakehouse Explorer, créez Files/javimapper/input/ et téléversez north.csv, south.csv et east.csv depuis labs/javimapper-mapping-lab/data/. Gardez les noms inchangés. La première cellule vérifie la présence des trois fichiers.

Les notebooks Spark Fabric acceptent les chemins relatifs du Lakehouse par défaut tels que Files/... ; pandas peut aussi utiliser le montage /lakehouse/default/Files/.... Ce notebook lit les petits fichiers avec la session Spark associée et convertit uniquement ces fixtures synthétiques de deux lignes en pandas pour l’adaptateur pandas. Consultez Charger des données dans un Lakehouse et les chemins NotebookUtils.

Utilisez cette structure dans le Lakehouse (le notebook d’onboarding crée le dossier de configuration versionné) :

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  (facultatif)
    └── output/
        └── mapping-report.html

Importer et exécuter le notebook

Ouvrez labs/javimapper-mapping-lab/notebooks/javimapper-mapping-lab.ipynb dans Fabric (téléversez-le ou importez-le dans le workspace). Gardez EXECUTION_MODE = "fabric", associez l’Environment publié et le Lakehouse par défaut, puis sélectionnez Run all. L’ordre est : (1) vérifier l’Environment et les fichiers, puis examiner les premières suggestions ; (2) révision et approbation humaine ; (3) mapping pandas ; (4) mapping Fabric Spark ; (5) réutilisation des alias sur les trois schémas ; (6) génération du rapport HTML. Les cinq champs cibles et les règles d’approbation de l’atelier local sont conservés.

Les captures ci-dessous sont des preuves des exécutions Microsoft Fabric fournies ; les tests automatisés du notebook sont des contrôles locaux distincts. L’exécution des six exercices a généré et enregistré le rapport, et la capture montre son affichage en ligne. Dans Fabric, displayHTML() est l’option compatible lorsque la sortie IPython ne s’affiche pas.

Notebook: javimapper-mapping-lab.ipynb

PySpark notebook14 cellules

Affichage en lecture seule du fichier notebook. Rien sur cette page n’exécute de code.

  1. Cellule 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. Cellule 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. Cellule 3PySparkCode61 lignes
    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}")

    Sortie

    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. Cellule 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. Cellule 5PySparkCode11 lignes
    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()))

    Sortie

    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. Cellule 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. Cellule 7PySparkCode7 lignes
    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)

    Sortie

    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. Cellule 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. Cellule 9PySparkCode7 lignes
    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)}")

    Sortie

    PySpark columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']
    PySpark rows match pandas: 2
  10. Cellule 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. Cellule 11PySparkCompare how many decisions remain after safe bulk approval, with and without aliases35 lignes
    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.")

    Sortie

    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. Cellule 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. Cellule 13PySparkCode42 lignes
    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__}")

    Sortie

    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. Cellule 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.

Examiner les résultats

Vérifiez que pandas et Spark produisent les cinq champs canoniques et les deux mêmes lignes North Market. Examinez les choix non résolus avant approbation. Les alias sont des suggestions vérifiées, pas des preuves. Les nombres de suggestions ne comparent que cette fixture fixe ; ils ne mesûrent ni la précision générale ni la productivité. Le rapport HTML est écrit dans Files/javimapper/output/mapping-report.html du Lakehouse par défaut. Comparez-le à vos notes de révision manuelle ; le notebook ne prétend pas mesûrer un gain de temps.

Utiliser JaviMapper dans un pipeline Fabric réel

Les deux notebooks suivants réutilisent le même Environment Fabric publié et un seul wheel JaviMapper 0.6.0b1. Associez cet Environment et le même Lakehouse par défaut aux deux notebooks. Chargez east.csv et east_delivery_02.csv dans Files/javimapper/input/. Le notebook d’intégration présente les propositions et consigne des décisions pédagogiques de référence pour ces données fictives ; ces décisions scriptées ne constituent pas l’approbation interactive d’un responsable des données.

Intégration d’un commerçant

Examinez le premier rapport, les avertissements sémantiques et les décisions explicites. Le notebook enregistre Files/javimapper/config/east-market/approved-mapping-v1.json. Ce JSON de mapping approuvé contient les schémas source et cible ainsi que le contrat source-cible utilisé par l’ingestion. Le fichier facultatif east-market-aliases-v1.json est différent : il contient des indications vérifiées pour de futurs rapprochements. Il ne remplace pas le mapping approuvé et l’ingestion récurrente ne le charge pas. Les fichiers versionnés sont créés sans écrasement ; choisissez un nouveau nom de version pour une approbation ultérieure.

Notebook: merchant-onboarding.ipynb

PySpark notebook10 cellules

Affichage en lecture seule du fichier notebook. Rien sur cette page n’exécute de code.

  1. Cellule 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. Cellule 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. Cellule 3PySparkCode49 lignes
    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)

    Sortie

    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. Cellule 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. Cellule 5PySparkCode19 lignes
    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.")

    Sortie

    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. Cellule 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. Cellule 7PySparkScripted teaching example only; this is not a live human approval workflow38 lignes
    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.")

    Sortie

    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. Cellule 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. Cellule 9PySparkCode34 lignes
    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']}")

    Sortie

    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. Cellule 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.

Ingestion récurrente

Le second notebook démarre dans un nouvel espace Python et charge directement le JSON enregistré dans OneLake. Il n’importe aucune variable du notebook d’intégration et ne lance pas de rapprochement flou. Il vérifie les noms, l’ordre et les types Spark des colonnes source, les champs cible obligatoires et les clés en double avant l’écriture. Toute différence arrête le traitement pour examen.

JaviMapper transforme les colonnes source approuvées en colonnes canoniques. Le notebook — pas JaviMapper — ajoute les métadonnées du commerçant, du fichier, de la livraison et de l’heure d’ingestion, définit la clé (source_merchant, transaction_id), vérifie les doublons, crée la table Delta du lab javimapper_lab_standardized_transactions et exécute MERGE. Résultats observés dans Fabric : première exécution entrée=2, insérées=2, correspondances/upserts=0, stockées=2, clés en double=0 ; relance entrée=2, insérées=0, correspondances/upserts=2, stockées=2, clés en double=0. La relance a mis à jour ingested_at_utc ; l’absence de doublons ne signifie donc pas des lignes identiques octet par octet. Cette table du lab est distincte des tables métier.

Notebook: recurring-ingestion.ipynb

PySpark notebook10 cellules

Affichage en lecture seule du fichier notebook. Rien sur cette page n’exécute de code.

  1. Cellule 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. Cellule 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. Cellule 3PySparkCode35 lignes
    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}")

    Sortie

    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. Cellule 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. Cellule 5PySparkCode13 lignes
    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}")

    Sortie

    Source columns and Spark type metadata match the approved onboarding schema.
    Input: east_delivery_02.csv; columns=['RefNo', 'DateOfSale', 'ClientNo', 'SaleValue', 'Currency']
  6. Cellule 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. Cellule 7PySparkCode31 lignes
    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}")

    Sortie

    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. Cellule 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. Cellule 9PySparkCode73 lignes
    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")

    Sortie

    [
      {
        "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. Cellule 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.

Les tests locaux utilisent un repli de persistance JSON, car l’environnement Spark local ne comprend pas le runtime Delta de Fabric. Vérifiez la création de la table Delta, MERGE, les chemins OneLake et la compatibilité de l’Environment dans un véritable espace Fabric avant de les considérer comme validés sur Fabric.

Dépannage et nettoyage

À la fin, arrêtez la session. Supprimez l’Environment, le notebook ou le Lakehouse uniquement s’ils ont été créés exclusivement pour cet atelier et ne sont plus nécessaires ; ne supprimez pas les ressources partagées.

Parcours local pandas/PySpark facultatif

Depuis la racine du dépôt :

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

Configurez Java compatible avec PySpark. Pour le notebook, remplacez EXECUTION_MODE par local ; il trouve les fixtures dans le dépôt ou le bundle privé extrait et ne crée une session Spark locale que si aucune n’existe. Le script écrit les résultats dans output/ du laboratoire. Le bundle et le wheel restent privés ; aucun n’est téléchargeable sur le site.

Avancé : créer le wheel depuis les sources

Depuis la racine du dépôt, créez un wheel local privé si nécessaire :

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

Vérifiez la version et les métadonnées LICENSE/NOTICE Apache-2.0. Le wheel ne doit contenir ni identifiants, ni données locales, ni environnement virtuel, ni chemin propre à une machine. Fabric fournit pandas et PySpark selon le runtime ; n’ajoutez pas de wheels facultatifs sans vérifier leur compatibilité. Conservez la sortie dans .codex-artifacts/, ignoré par Git, jamais dans public/ ou dist/.