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: compute startup versus execution time in Microsoft Fabric

When a notebook “takes three minutes”, that time is spent in very different places: waiting for a Spark session, initializing the first Spark job, and actually running your code. They have different causes and different fixes, and only some of them can be measured from inside the notebook. This lab separates them with JaviPerf, an experimental library, on synthetic data, and walks through the first live run in Microsoft Fabric.

1. Why measure startup separately?

A notebook cell can only run once its Spark session is ready, so no cell can time the period before it starts. Everything a notebook measures begins after the session became available. Inside the notebook, two more effects distort naive timings:

And outside the notebook, Fabric reports durations with their own boundaries: the session startup in the session information panel, and the Spark application’s elapsed time in monitoring, which keeps growing while the session stays open. These measure different things and are never added together.

  1. Startup beginsRun all selectedInvisible to every cell
  2. Fabric reportsSession readySession information, startup duration
  3. Notebook clockFirst code cellUpper bound for readiness
  4. JaviPerfFirst Spark actionIncludes one-time overhead
  5. JaviPerfDefine transformationLazy, no Spark job
  6. JaviPerfMaterializeAn action processes the data
  7. JaviPerfReportSources and clocks labelled
One notebook run, and who can measure each part. Session startup ends before any cell can run, so Fabric or a person reports it, not the notebook. The notebook measures everything after its first cell. None of these durations are added together.
Phase Measured by Why
Session startup Fabric’s View session information panel; or you, with a clock (worksheet); optionally a Livy session JSON No cell can run before the session is ready
First Spark action The notebook The first job pays one-time costs that later jobs don’t
Define vs materialize The notebook, with Spark job counts Transformations are lazy: defining one does no work
Python UDF vs built-in The notebook, with an output check Compare only when both versions return the same rows
Plan observations The notebook (no job runs) Static: what the plan contains, not how long it took

A reused session (an existing interactive session, or a shared high-concurrency session) has no startup in that run: JaviPerf reports it as not applicable, never as zero. A missing value is unavailable, never zero.

Prerequisites

Build the current wheel locally

The editable install and wheel build affect your local development environment only. From the repository root, run:

python -m pip install -e "./libraries/javiperf[dev,spark]"
python -m build --wheel --outdir .codex-artifacts/private-wheels ./libraries/javiperf

The current package metadata in libraries/javiperf/pyproject.toml produces .codex-artifacts/private-wheels/javiperf-0.2.1-py3-none-any.whl. The build does not upload it. To repeat the Environment steps below with 0.2.1, upload that locally built file. The evidence on this page records the earlier 0.2.0 run; its download link is a development-only copy of that historical wheel. The 0.2.1 duration-only reporting has not been executed in Fabric.

Download the historical wheel

The link works only on the local development server, over localhost. It serves the historical JaviPerf 0.2.0 wheel that was used in the live run, built with python -m build --wheel --outdir .codex-artifacts/private-wheels libraries/javiperf. JaviPerf is not published to PyPI, and the wheel is never part of the public site.

2. Install several libraries in one Environment

The live run reused the Environment from the JaviMapper lab, env_javimapper_lab, instead of creating a new one. An Environment can hold several custom libraries, so one published Environment can serve the notebooks of both labs.

  1. Open env_javimapper_lab (or create an Environment on Runtime 2.0 if you don’t have one).
  2. Select Custom libraries and the Full mode tab.
  3. Keep JaviMapper installed. Don’t remove or re-upload it.
  4. Upload javiperf-0.2.0-py3-none-any.whl.
  5. Save: the wheel shows as Saved and New, and the Pending changes pane lists it.
  6. Select Publish all and wait.
  7. Confirm that both wheels show Success.

Reusing the Environment saves a second publish and keeps both labs on the same runtime. It also couples them: every notebook attached to the Environment loads both libraries, and a future version of either could declare a dependency that conflicts with the other. JaviPerf’s core has no third-party dependencies, which keeps that risk small here, but check the publish result after every upgrade rather than assuming compatibility. Microsoft documents that Full-mode libraries are installed when a session starts and can lengthen startup; Section 7 shows what one run reported.

3. Import the notebook

Import labs/javiperf-fabric-performance-lab/notebooks/javiperf-fabric-performance-lab.ipynb from your copy of the repository (Import notebook in the workspace). In the notebook’s toolbar, select the published Environment (env_javimapper_lab in the live run). Then you can verify the install in a new cell: import javiperf; print(javiperf.__version__) prints 0.2.0.

The notebook defaults to EXECUTION_MODE = "fabric" and uses the spark session Fabric provides. Its 18 cells are shown at the end of this page exactly as saved in the repository, with outputs from a local run.

4. Attach the Lakehouse

Create a lakehouse for the lab (lh_javiperf_lab in the live run) and add it to the notebook as the default. The lab generates its own synthetic data, so it needs no Delta tables and no input CSV files. The lakehouse is only where the HTML report is written: Files/javiperf-lab/output/javiperf-lab-report.html.

5. Run the experiment

Select Run all. The parameters cell keeps the default workload, ROWS = 200_000 synthetic rows, with REPEAT = 3 measured runs per side. The exercises then:

  1. First Spark action. spark.range(1).count() reads no data; it is timed, then repeated to show what part was one-time cost.
  2. Lazy transformation. Defining an aggregation is timed together with the Spark job count: zero jobs.
  3. Materialized execution. The noop writer runs the whole plan without writing anything; now jobs run.
  4. Python UDF versus built-in. The same cleanup, as a Python UDF and with upper(trim(...)), run alternately after a warm-up, with the outputs checked for equality outside the timed region.
  5. Plan analysis. Static observations from explain(): no job runs.
  6. Report. One self-contained HTML file, displayed in the notebook and saved to the lakehouse.

Notebook: javiperf-fabric-performance-lab.ipynb

PySpark notebookShowing cells 7, 8, 9, 10 of 18Open the full notebook

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

  1. Cell 7MarkdownExercise 2: the first Spark action
    Exercise 2: the first Spark action

    A ready session hasn't run any Spark job yet. The first action pays for job scheduling, executor start and code paths loaded for the first time. first_action runs Spark's smallest action, spark.range(1).count(), which reads no data. Running the same action again shows how much of that was one-time cost.

  2. Cell 8PySparkExercise 2: the first Spark action9 lines
    PySpark
    timeline = Timeline("lab run")
    timeline.mark_start()
    jobs = first_action(timeline, spark)
    with timeline.phase("second_small_action", note="the same spark.range(1).count(), once more"):
        spark.range(1).count()
    first, second = timeline.get("first_action"), timeline.get("second_small_action")
    print(f"first action: {first.duration_s:.3f} s ({jobs} Spark job(s)); same action again: {second.duration_s:.3f} s")
    if "not the session's first action" in first.note:
        print("Note:", first.note)

    Output

    first action: 4.801 s (2 Spark job(s)); same action again: 0.317 s
  3. Cell 9MarkdownExercise 3: Spark is lazy
    Exercise 3: Spark is lazy

    Defining a transformation returns at once and starts no Spark job. Only an action executes it. The noop writer runs the whole plan without writing or collecting anything.

  4. Cell 10PySparkExercise 3: define vs materialize15 lines
    PySpark
    from pyspark.sql import functions as F
    
    source = spark.range(0, rows).select("id", F.concat(F.lit(" c"), (F.col("id") % 1000).cast("string"), F.lit(" ")).alias("code"))
    
    probe = SparkJobProbe(spark)
    probe.before()
    with timeline.phase("define_transformation"):
        totals = source.groupBy((F.col("id") % 100).alias("bucket")).agg(F.count("*").alias("n"))
    defined_jobs = probe.after()["spark_jobs"]
    probe.before()
    with timeline.phase("transform", note="noop write: executes the aggregation"):
        materialize_noop(totals)
    executed_jobs = probe.after()["spark_jobs"]
    print(f"define: {timeline.get('define_transformation').duration_s:.3f} s, {defined_jobs} Spark job(s)")
    print(f"materialize: {timeline.get('transform').duration_s:.3f} s, {executed_jobs} Spark job(s)")

    Output

    define: 0.078 s, 0 Spark job(s)
    materialize: 1.993 s, 2 Spark job(s)

Not shown here: cells 1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18. Open the full notebook (all 18 cells, in order)

Notebook: javiperf-fabric-performance-lab.ipynb

PySpark notebookShowing cells 11, 12, 13, 14 of 18Open the full notebook

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

  1. Cell 11MarkdownExercise 4: Python UDF versus built-in functions
    Exercise 4: Python UDF versus built-in functions

    The same cleanup, twice. Both versions are executed by the same explicit action, alternately, and their outputs are checked for equality outside the timed region. A local result says nothing about Fabric: measure here.

  2. Cell 12PySparkExercise 4: UDF vs built-in17 lines
    PySpark
    from pyspark.sql.types import StringType
    
    clean_udf = F.udf(lambda s: s.strip().upper(), StringType())
    
    def with_udf():
        return source.select("id", clean_udf("code").alias("code"))
    
    def with_builtin():
        return source.select("id", F.upper(F.trim("code")).alias("code"))
    
    with timeline.phase("udf_vs_builtin", note="warm-up, measured runs and the equivalence check"):
        comparison = compare_dataframes("Python UDF vs built-in", with_udf, with_builtin, action=materialize_noop,
                                        spark=spark, warmup=1, repeat=REPEAT, metadata={"rows": rows, "data": "synthetic"})
    b, c = comparison.baseline.summary, comparison.candidate.summary
    print(f"outputs: {comparison.equivalence}")
    print(f"verdict: {comparison.verdict} - {comparison.verdict_reason}")
    print(f"spread (CV): UDF {b.cv:.1%}, built-in {c.cv:.1%} over {b.count} runs each")

    Output

    outputs: equivalent
    verdict: candidate_faster - Every successful candidate run was faster than every successful baseline run in this session.
    spread (CV): UDF 12.8%, built-in 4.3% over 3 runs each
  3. Cell 13MarkdownExercise 5: what the plans contain
    Exercise 5: what the plans contain

    Static observations from explain(): no job runs here. Compare them with the Spark advisor's messages under the cells above and with the Spark application detail page, which show what actually ran.

  4. Cell 14PySparkExercise 5: plan observations10 lines
    PySpark
    plans = [analyze_dataframe(with_udf(), label="Python UDF version"),
             analyze_dataframe(with_builtin(), label="built-in version"),
             analyze_dataframe(totals, label="aggregation")]
    print("Observed in the plans:")
    for p in plans:
        print(f"  {p.label}: {', '.join(p.codes) or 'no findings'}")
    print("To investigate (hypotheses, not fixes):")
    for p in plans:
        for f in p.findings:
            print(f"  {p.label} / {f.code}: {f.investigate[0]}")

    Output

    Observed in the plans:
      Python UDF version: PYTHON_UDF
      built-in version: no findings
      aggregation: SHUFFLE_EXCHANGE
    To investigate (hypotheses, not fixes):
      Python UDF version / PYTHON_UDF: Check whether a built-in function in pyspark.sql.functions expresses the same logic.
      aggregation / SHUFFLE_EXCHANGE: Check the shuffle read and write sizes of the matching stages in the Spark UI or the Fabric Spark application detail page (Jobs and stages) on representative data.

Not shown here: cells 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18. Open the full notebook (all 18 cells, in order)

The outputs above are from a local PySpark run on a developer machine, not from Fabric: they show the shape of the results, not Fabric performance. The live run’s notebook outputs for these cells were not saved, so this page reports no Fabric number for the first action, the laziness exercise or the UDF comparison.

Read a comparison’s verdict together with its output check: a faster version that returns different rows is not an improvement.

6. Find the session information

The notebook can’t see its own startup, but Fabric reports it. In the live run, this is where it was:

  1. Return to the notebook (with its session still running).
  2. In the toolbar, open the arrow next to Standard session.
  3. Select View session information.
  4. In the panel, find Startup details.
  5. Read Startup duration and Delay reason(s). Note the Session source and Runtime version too.

Copy only those values. The panel’s Session ID and its Diagnostics JSON contain identifiers (session, notebook, workspace) and don’t belong in a lab worksheet or a shared report. The Diagnostics label at the bottom of the Spark application’s monitoring page was not clickable in this run: use the notebook’s session menu instead.

The lab’s worksheet and notebook were written before the live run and refer to Session Details (Session Start Insights). In this run, the startup details were found in the View session information panel described above.

7. Interpret the startup result

What this one value tells you, and what it doesn’t:

Why it is still useful: it is a real, sourced number for the part of a run that no notebook can time, and it shows where to read it. Conclusions need repeated fresh sessions, ideally against an Environment without the custom libraries.

Record it. Copy the values into the worksheet as displayed, with blank request and ready times (you didn’t record them):

run_label,run_selected_utc,session_ready_utc,readiness_signal,session_status,pool_type,runtime_version,environment,environment_publish_mode,delay_reason,capacity_notes,notes,session_type,reported_startup_duration,reported_startup_source
first live run,,,,fresh,starter,Runtime 2.0 (Spark 4.1 Delta 4.2),env_javimapper_lab,full,CustomLibraries,,read in View session information,standard,28 sec 843 ms,fabric_session_information

JaviPerf 0.2.1 (local only, not yet run in Fabric) reads the last three columns as a duration-only observation: it keeps 28.843 s with its source, never invents timestamps from it, and never adds it to notebook timings. The 0.2.0 wheel used in the live run ignores those columns.

8. Read the Spark application monitoring

The Spark application’s monitoring page (open the notebook’s run from Monitor) shows the session’s Spark jobs and its run details.

In the capture, jobs 6 to 22 had succeeded, with durations from 42 ms to 2 sec 226 ms, and the run details showed a total and running duration of 3 min 52 sec with 0 sec queued, while the application was still Running.

  • Session startupFabric Session information
    1. Compute requested
    2. Session ready
  • Spark applicationMonitoring, total and running
    1. Application starts
    2. All jobs of the session
    3. Still running while open
  • One Spark jobMonitoring, Jobs tab
    1. Job submitted
    2. Job finished
  • JaviPerf phaseNotebook clock
    1. Phase starts in a cell
    2. Phase ends in a cell
Four durations, four different boundaries. Each duration starts and ends at different points, and some overlap. They are read side by side; adding them would count the same time twice.

9. Understand the JaviPerf report

The report is one HTML file with no scripts and no external resources, shown with displayHTML and saved to Files/javiperf-lab/output/javiperf-lab-report.html.

In the live run, the report’s Session start table showed Startup (request to ready): unavailable, with its timestamps not recorded. That was correct: when the notebook ran, no startup observation had been entered, and JaviPerf reports a missing value as unavailable, never as zero. The 28.843-second value was read afterwards in the session information panel. The report from that run is kept as it was; it is not rewritten to include a value it didn’t have.

What the report contains, and what this run provided:

Part In the live run
Session startup Unavailable when the report was built; Fabric later reported 28.843 s (Section 7)
Measured phases and the UDF vs built-in comparison Produced in Fabric, but the values were not captured; this page reports none
Plan observations Shown: for example, PYTHON_UDF (a BatchEvalPython operator) in the UDF version’s plan
Investigations to validate Hypotheses from the plans, such as checking whether a built-in function can replace the UDF
Limitations Always included: timings describe this session only, and a faster run doesn’t imply lower cost

Plan observations are static: they describe what a plan contains, not how long it took or whether it is a problem.

10. Conclusion and next experiments

What the first live run demonstrated:

What it didn’t demonstrate: any performance difference, any cost effect, or the share of startup caused by each library. None of the experiments below has been run yet:

The complete notebook

Every cell of the notebook, as saved in the repository, with its outputs from a local run:

Notebook: javiperf-fabric-performance-lab.ipynb

PySpark notebook18 cells

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

  1. Cell 1MarkdownJaviPerf in Microsoft Fabric: startup, first action and execution, measured separately

    JaviPerf in Microsoft Fabric: startup, first action and execution, measured separately

    JaviPerf 0.2 is experimental. This notebook separates the time a Spark session takes to become available from the time your code takes to run, using synthetic data only. It never creates Fabric items, never calls Fabric APIs and never caches data. Run it in a dedicated lab workspace, not a production one.

    Before you select Run all, open the session-start worksheet: Exercise 1 starts before the first cell runs.

  2. Cell 2PySparkRun this cell first. Its start is an upper bound for when the session became ready4 lines
    PySpark
    # Run this cell first. Its start is an upper bound for when the session became ready.
    from javiperf.fabric import first_cell_mark
    
    FIRST_CELL = first_cell_mark()
  3. Cell 3PySparkParametersParameters15 lines
    PySpark
    # Parameters
    EXECUTION_MODE = "fabric"          # "fabric" (default) or "local"
    ROWS = 200_000                     # small synthetic workload
    REPEAT = 3                         # measured runs per side in Exercise 4
    LARGE_WORKLOAD_ROWS = None         # for example 10_000_000; needs the confirmation below
    CONFIRM_LARGE_WORKLOAD = ""        # type exactly: I understand this consumes capacity
    STOP_SESSION_AT_END = False        # True stops this Spark session after the report
    
    # Exercise 1: paste what you recorded on the worksheet (UTC, ISO 8601 with Z), or leave None.
    RUN_SELECTED_UTC = None            # e.g. "2026-12-01T09:00:03Z": when you selected Run all
    SESSION_READY_UTC = None           # e.g. "2026-12-01T09:00:11Z": when the session status showed ready
    SESSION_STATUS = "unknown"         # fresh | existing_interactive | high_concurrency_reused | unknown
    POOL_TYPE = "unknown"              # starter | custom | custom_live | unknown
    DELAY_REASON = None                # as shown in Session Start Insights (Session Details), if any
    LIVY_SESSION_JSON = None           # optional: a Livy session JSON you saved yourself, e.g. "Files/javiperf-lab/livy-session.json"
  4. Cell 4PySparkCode32 lines
    PySpark
    import sys
    from pathlib import Path
    
    import javiperf
    from javiperf import SessionObservation, Timeline, Timestamp, build_report, render_html
    from javiperf.environment import capture_environment
    from javiperf.fabric import observation_from_livy, parse_livy_session, runtime_facts
    from javiperf.spark import (SparkJobProbe, analyze_dataframe, benchmark_dataframe, compare_dataframes, first_action,
                                materialize_noop)
    
    CONFIRMATION = "I understand this consumes capacity"
    MAX_ROWS_WITHOUT_CONFIRMATION = 1_000_000
    rows = ROWS
    if LARGE_WORKLOAD_ROWS:
        if CONFIRM_LARGE_WORKLOAD != CONFIRMATION:
            raise ValueError(f"LARGE_WORKLOAD_ROWS is set: also set CONFIRM_LARGE_WORKLOAD = {CONFIRMATION!r} to run it.")
        rows = int(LARGE_WORKLOAD_ROWS)
    if rows > MAX_ROWS_WITHOUT_CONFIRMATION and CONFIRM_LARGE_WORKLOAD != CONFIRMATION:
        raise ValueError(f"{rows:,} rows needs CONFIRM_LARGE_WORKLOAD = {CONFIRMATION!r}.")
    
    if EXECUTION_MODE == "fabric":
        OUTPUT_DIR = Path("/lakehouse/default/Files/javiperf-lab/output")  # the attached default lakehouse
    else:
        from pyspark.sql import SparkSession
        spark = SparkSession.builder.master("local[2]").config("spark.ui.enabled", "false").getOrCreate()
        OUTPUT_DIR = Path("output")
    
    env = capture_environment(spark)
    print(f"Execution mode: {EXECUTION_MODE}" + (" (saved outputs were captured locally, not in Fabric)" if EXECUTION_MODE == "local" else ""))
    print(f"JaviPerf {javiperf.__version__} | Python {sys.version.split()[0]} | Spark {spark.version} | rows per run: {rows:,}")
    print("Effective Spark settings:", {k.split('spark_conf.')[1]: v for k, v in env.items() if k.startswith("spark_conf.")})
    print("Runtime facts (no names or IDs):", runtime_facts() or "not available outside Fabric")

    Output

    Execution mode: local (saved outputs were captured locally, not in Fabric)
    JaviPerf 0.2.0 | Python 3.13.17 | Spark 4.1.4 | rows per run: 200,000
    Effective Spark settings: {'spark.sql.adaptive.coalescePartitions.enabled': 'true', 'spark.sql.adaptive.enabled': 'true', 'spark.sql.adaptive.skewJoin.enabled': 'true', 'spark.sql.autoBroadcastJoinThreshold': '10485760b', 'spark.sql.execution.arrow.pyspark.enabled': 'false', 'spark.sql.files.maxPartitionBytes': '134217728b', 'spark.sql.shuffle.partitions': '200'}
    Runtime facts (no names or IDs): not available outside Fabric
  5. Cell 5MarkdownExercise 1: compute startup, measured outside the notebook
    Exercise 1: compute startup, measured outside the notebook

    Code can only run once the session is ready, so no cell can time its own session start. Record it from outside:

    1. Before selecting Run all, note the time on the worksheet (run_selected_utc).
    2. Note when the session status shows the session is ready (session_ready_utc) and what you saw (readiness_signal).
    3. Open Session Details (Session Start Insights) and copy the session source (starter pool or on-demand) and any delay reason.
    4. Record whether this was a fresh session or an existing or shared one. A reused session has no startup to measure.

    Then paste the values into the parameters cell. Missing values are reported as unavailable, never as zero.

  6. Cell 6PySparkCode23 lines
    PySpark
    def stamp(value, label):
        return Timestamp(value, "manual", "observer", 2.0, label) if value else None
    
    session = SessionObservation(
        "this run",
        requested_at=stamp(RUN_SELECTED_UTC, "Run all selected (manual reading)"),
        ready_at=stamp(SESSION_READY_UTC, "session shown as ready (manual reading)") or (
            FIRST_CELL if RUN_SELECTED_UTC else None),
        status=SESSION_STATUS, pool_type=POOL_TYPE, runtime_version=env.get("spark_version"), delay_reason=DELAY_REASON,
    )
    sessions = [session]
    if LIVY_SESSION_JSON:
        import json
        record = parse_livy_session(json.loads(Path("/lakehouse/default/" + LIVY_SESSION_JSON).read_text()))
        sessions.append(observation_from_livy(record, label="Livy session (API proxy)", status=SESSION_STATUS, pool_type=POOL_TYPE))
    
    for s in sessions:
        startup = s.startup
        value = "unavailable" if startup.status == "unavailable" else (
            "not applicable" if startup.status == "not_applicable" else f"{startup.duration_s:.1f} s ({startup.quality})")
        print(f"{s.label}: session status {s.status}, startup {value}")
        if startup.reason:
            print("  ", startup.reason)

    Output

    this run: session status unknown, startup unavailable
       The start and end timestamps of the session startup were not recorded.
  7. Cell 7MarkdownExercise 2: the first Spark action
    Exercise 2: the first Spark action

    A ready session hasn't run any Spark job yet. The first action pays for job scheduling, executor start and code paths loaded for the first time. first_action runs Spark's smallest action, spark.range(1).count(), which reads no data. Running the same action again shows how much of that was one-time cost.

  8. Cell 8PySparkCode9 lines
    PySpark
    timeline = Timeline("lab run")
    timeline.mark_start()
    jobs = first_action(timeline, spark)
    with timeline.phase("second_small_action", note="the same spark.range(1).count(), once more"):
        spark.range(1).count()
    first, second = timeline.get("first_action"), timeline.get("second_small_action")
    print(f"first action: {first.duration_s:.3f} s ({jobs} Spark job(s)); same action again: {second.duration_s:.3f} s")
    if "not the session's first action" in first.note:
        print("Note:", first.note)

    Output

    first action: 4.801 s (2 Spark job(s)); same action again: 0.317 s
  9. Cell 9MarkdownExercise 3: Spark is lazy
    Exercise 3: Spark is lazy

    Defining a transformation returns at once and starts no Spark job. Only an action executes it. The noop writer runs the whole plan without writing or collecting anything.

  10. Cell 10PySparkCode15 lines
    PySpark
    from pyspark.sql import functions as F
    
    source = spark.range(0, rows).select("id", F.concat(F.lit(" c"), (F.col("id") % 1000).cast("string"), F.lit(" ")).alias("code"))
    
    probe = SparkJobProbe(spark)
    probe.before()
    with timeline.phase("define_transformation"):
        totals = source.groupBy((F.col("id") % 100).alias("bucket")).agg(F.count("*").alias("n"))
    defined_jobs = probe.after()["spark_jobs"]
    probe.before()
    with timeline.phase("transform", note="noop write: executes the aggregation"):
        materialize_noop(totals)
    executed_jobs = probe.after()["spark_jobs"]
    print(f"define: {timeline.get('define_transformation').duration_s:.3f} s, {defined_jobs} Spark job(s)")
    print(f"materialize: {timeline.get('transform').duration_s:.3f} s, {executed_jobs} Spark job(s)")

    Output

    define: 0.078 s, 0 Spark job(s)
    materialize: 1.993 s, 2 Spark job(s)
  11. Cell 11MarkdownExercise 4: Python UDF versus built-in functions
    Exercise 4: Python UDF versus built-in functions

    The same cleanup, twice. Both versions are executed by the same explicit action, alternately, and their outputs are checked for equality outside the timed region. A local result says nothing about Fabric: measure here.

  12. Cell 12PySparkCode17 lines
    PySpark
    from pyspark.sql.types import StringType
    
    clean_udf = F.udf(lambda s: s.strip().upper(), StringType())
    
    def with_udf():
        return source.select("id", clean_udf("code").alias("code"))
    
    def with_builtin():
        return source.select("id", F.upper(F.trim("code")).alias("code"))
    
    with timeline.phase("udf_vs_builtin", note="warm-up, measured runs and the equivalence check"):
        comparison = compare_dataframes("Python UDF vs built-in", with_udf, with_builtin, action=materialize_noop,
                                        spark=spark, warmup=1, repeat=REPEAT, metadata={"rows": rows, "data": "synthetic"})
    b, c = comparison.baseline.summary, comparison.candidate.summary
    print(f"outputs: {comparison.equivalence}")
    print(f"verdict: {comparison.verdict} - {comparison.verdict_reason}")
    print(f"spread (CV): UDF {b.cv:.1%}, built-in {c.cv:.1%} over {b.count} runs each")

    Output

    outputs: equivalent
    verdict: candidate_faster - Every successful candidate run was faster than every successful baseline run in this session.
    spread (CV): UDF 12.8%, built-in 4.3% over 3 runs each
  13. Cell 13MarkdownExercise 5: what the plans contain
    Exercise 5: what the plans contain

    Static observations from explain(): no job runs here. Compare them with the Spark advisor's messages under the cells above and with the Spark application detail page, which show what actually ran.

  14. Cell 14PySparkCode10 lines
    PySpark
    plans = [analyze_dataframe(with_udf(), label="Python UDF version"),
             analyze_dataframe(with_builtin(), label="built-in version"),
             analyze_dataframe(totals, label="aggregation")]
    print("Observed in the plans:")
    for p in plans:
        print(f"  {p.label}: {', '.join(p.codes) or 'no findings'}")
    print("To investigate (hypotheses, not fixes):")
    for p in plans:
        for f in p.findings:
            print(f"  {p.label} / {f.code}: {f.investigate[0]}")

    Output

    Observed in the plans:
      Python UDF version: PYTHON_UDF
      built-in version: no findings
      aggregation: SHUFFLE_EXCHANGE
    To investigate (hypotheses, not fixes):
      Python UDF version / PYTHON_UDF: Check whether a built-in function in pyspark.sql.functions expresses the same logic.
      aggregation / SHUFFLE_EXCHANGE: Check the shuffle read and write sizes of the matching stages in the Spark UI or the Fabric Spark application detail page (Jobs and stages) on representative data.
  15. Cell 15MarkdownExercise 6: the report
    Exercise 6: the report

    One self-contained HTML file: session start (with its source), the phase timeline, measurements, plan observations and the limitations. It is shown below and saved to the lakehouse under Files/javiperf-lab/output/.

  16. Cell 16PySparkCode11 lines
    PySpark
    timeline.mark_end()
    report = build_report(title="JaviPerf Fabric lab", timelines=[timeline], sessions=sessions, comparisons=[comparison],
                          plan_analyses=plans, environment=env,
                          notes=[f"Execution mode: {EXECUTION_MODE}.", "Synthetic data. Measurements describe this session only."])
    html = render_html(report)
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    (OUTPUT_DIR / "javiperf-lab-report.html").write_text(html, encoding="utf-8")
    if EXECUTION_MODE == "fabric":
        displayHTML(html)
    print(f"report saved: {OUTPUT_DIR.name}/javiperf-lab-report.html ({len(html) // 1024} KB, no scripts, no external resources)")
    print("unaccounted time in this timeline:", timeline.unaccounted.status, "-", timeline.unaccounted.reason)

    Output

    report saved: output/javiperf-lab-report.html (21 KB, no scripts, no external resources)
    unaccounted time in this timeline: measured - End-to-end time minus the measured top-level phases (gaps between cells, idle time, notebook overhead).
  17. Cell 17MarkdownClean up
    Clean up

    Stop the session when you are done (or set STOP_SESSION_AT_END = True and rerun this cell), then delete the lab workspace or its items when the evidence is saved.

  18. Cell 18PySparkCode5 lines
    PySpark
    if EXECUTION_MODE == "fabric" and STOP_SESSION_AT_END:
        notebookutils.session.stop()
        print("Session stop requested.")
    else:
        print("Session left running. Stop it from the toolbar, or set STOP_SESSION_AT_END = True.")

    Output

    Session left running. Stop it from the toolbar, or set STOP_SESSION_AT_END = True.

Safety, capacity and cleanup

Repeat the run

The checklist for a live run, and what to capture, is in labs/javiperf-fabric-performance-lab/FABRIC_TEST_PLAN.md. For a comparable series, record each run on the worksheet: whether the session was fresh or reused, the pool, the Environment and its publish mode, and the startup duration and delay reason as displayed.

Optional local route

python -m pip install -e "./libraries/javiperf[spark]"
python labs/javiperf-fabric-performance-lab/build_notebook.py

The script executes every cell locally (it sets EXECUTION_MODE to local after the parameters cell) and saves the outputs. Local numbers describe your machine only.