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:
- Laziness. Defining a Spark transformation returns almost immediately and processes no data. Only an action (a count, a write) runs it. A “fast” transformation cell usually measured nothing.
- First-action overhead. The first Spark job after a session starts pays one-time costs (job scheduling, executor and code initialization) that the same job, run again, doesn’t repeat.
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.
- Startup beginsRun all selectedInvisible to every cell
- Fabric reportsSession readySession information, startup duration
- Notebook clockFirst code cellUpper bound for readiness
- JaviPerfFirst Spark actionIncludes one-time overhead
- JaviPerfDefine transformationLazy, no Spark job
- JaviPerfMaterializeAn action processes the data
- JaviPerfReportSources and clocks labelled
| 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
- A Microsoft Fabric workspace used only for labs, on a capacity you may use for testing. Not a production workspace.
- Permission to edit an Environment and to create a lakehouse and a notebook in that workspace.
- The JaviBuilds repository on your machine, with
npm run devrunning (for the wheel download). - Optional: a clock showing UTC with seconds, if you also want to record your own request and ready times.
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.
- Open
env_javimapper_lab(or create an Environment on Runtime 2.0 if you don’t have one). - Select Custom libraries and the Full mode tab.
- Keep JaviMapper installed. Don’t remove or re-upload it.
- Upload
javiperf-0.2.0-py3-none-any.whl. - Save: the wheel shows as Saved and New, and the Pending changes pane lists it.
- Select Publish all and wait.
- 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:
- First Spark action.
spark.range(1).count()reads no data; it is timed, then repeated to show what part was one-time cost. - Lazy transformation. Defining an aggregation is timed together with the Spark job count: zero jobs.
- Materialized execution. The
noopwriter runs the whole plan without writing anything; now jobs run. - 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. - Plan analysis. Static observations from
explain(): no job runs. - Report. One self-contained HTML file, displayed in the notebook and saved to the lakehouse.
Notebook: javiperf-fabric-performance-lab.ipynb
Read-only view of the notebook file. Nothing on this page runs code.
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_actionruns 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.Cell 8PySparkExercise 2: the first Spark action9 lines
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
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
noopwriter runs the whole plan without writing or collecting anything.Cell 10PySparkExercise 3: define vs materialize15 lines
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
Read-only view of the notebook file. Nothing on this page runs code.
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.
Cell 12PySparkExercise 4: UDF vs built-in17 lines
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
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.Cell 14PySparkExercise 5: plan observations10 lines
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:
- Return to the notebook (with its session still running).
- In the toolbar, open the arrow next to Standard session.
- Select View session information.
- In the panel, find Startup details.
- 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:
- It is Fabric’s own report of how long this session took to start. It is not a manual estimate, not a median, and not the time the notebook’s code took.
- CustomLibraries is the category Fabric reported for the delay: the Environment’s custom libraries were part of this start. It does not say how much of the 28.843 seconds they caused, and nothing here says how much JaviMapper or JaviPerf contributed individually.
- The panel shows no request or ready timestamps, so the duration can’t be placed on the notebook’s clock. It is displayed to the millisecond; Fabric doesn’t document the accuracy behind that display.
- It is one observation with no baseline. There is no run of the same notebook without the custom libraries to compare with, so it shows neither that the libraries slowed startup nor by how much. Microsoft documents that starter pools can provide sessions in seconds when pre-warmed capacity is available and that Full-mode libraries can add minutes; a single run neither confirms nor contradicts either.
- It says nothing about capacity cost on its own.
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
- Compute requested
- Session ready
- Spark applicationMonitoring, total and running
- Application starts
- All jobs of the session
- Still running while open
- One Spark jobMonitoring, Jobs tab
- Job submitted
- Job finished
- JaviPerf phaseNotebook clock
- Phase starts in a cell
- Phase ends in a cell
- 3 min 52 sec is the application’s elapsed time at the moment of the capture. It grows while the session stays open, idle time included. It is not the startup and not the processing time, and it is not added to the 28.843 seconds: their boundaries and clocks differ.
- A job’s duration covers one Spark job. One notebook action can start several jobs, and the jobs don’t map one to one onto the exercises.
- Data processing is what the materialized phases measure, inside the notebook.
- First-action overhead appears as the difference between the first small action and the same action repeated.
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:
- Two custom wheels, JaviMapper 0.6.0b1 and JaviPerf 0.2.0, published together in one Full-mode Environment, and both showed Success.
- The lab notebook ran in Fabric on Runtime 2.0 with synthetic data, analyzed plans and produced its HTML report in the lakehouse.
- The report handled the missing startup correctly, as unavailable.
- Fabric reported one session startup of 28.843 seconds, from a starter pool, with delay reason CustomLibraries.
- The Spark application’s monitoring duration is a separate measurement from session startup.
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:
- Several fresh sessions, to see how much startup varies.
- Runs in an existing session, where startup is not applicable.
- Another pool configuration where your capacity supports it.
- The same notebook with an Environment without custom libraries, as a baseline for shared Environment dependencies.
- The first Spark action measured repeatedly across fresh sessions.
- The Python UDF and built-in versions at several controlled row counts.
- The Spark advisor’s messages for these cells, compared with JaviPerf’s plan observations.
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
Read-only view of the notebook file. Nothing on this page runs code.
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.
Cell 2PySparkRun this cell first. Its start is an upper bound for when the session became ready4 lines
# 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()Cell 3PySparkParametersParameters15 lines
# 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"Cell 4PySparkCode32 lines
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 FabricCell 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:
- Before selecting Run all, note the time on the worksheet (
run_selected_utc). - Note when the session status shows the session is ready (
session_ready_utc) and what you saw (readiness_signal). - Open Session Details (Session Start Insights) and copy the session source (starter pool or on-demand) and any delay reason.
- 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.
- Before selecting Run all, note the time on the worksheet (
Cell 6PySparkCode23 lines
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.
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_actionruns 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.Cell 8PySparkCode9 lines
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
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
noopwriter runs the whole plan without writing or collecting anything.Cell 10PySparkCode15 lines
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)
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.
Cell 12PySparkCode17 lines
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
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.Cell 14PySparkCode10 lines
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.
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/.Cell 16PySparkCode11 lines
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).
Cell 17MarkdownClean up
Clean up
Stop the session when you are done (or set
STOP_SESSION_AT_END = Trueand rerun this cell), then delete the lab workspace or its items when the evidence is saved.Cell 18PySparkCode5 lines
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
- The default workload is 200,000 synthetic rows. Above 1,000,000 rows the notebook stops unless you set
CONFIRM_LARGE_WORKLOAD = "I understand this consumes capacity". It never runs 10 or 100 million rows by default. - It doesn’t cache data, change Spark settings or write tables. Every action uses the
noopwriter; only the report is written. - Watch consumption in the Fabric Capacity Metrics app if you have access. A faster run isn’t evidence of a lower bill: capacity consumption depends on how compute is metered.
- Stop the session when you’re done, from the toolbar or with
STOP_SESSION_AT_END = True. Otherwise the Spark application keeps running, and its monitoring duration keeps growing. - Delete the lab notebook and lakehouse once you’ve saved your evidence. If you reused another lab’s Environment, remove the JaviPerf wheel from it and publish again, or keep it if both labs still need it.
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.