Disponibilidad de los paquetes: JaviMapper es una beta no publicada y JaviPerf es experimental. Ninguno tiene una versión pública en PyPI ni un wheel público, y el repositorio del código fuente es privado. Los visitantes no pueden obtener ni compilar estos paquetes desde este sitio. Los pasos de instalación en Fabric requieren un wheel ya autorizado y suministrado de forma privada; sin ese acceso, no se pueden ejecutar los ejercicios.

Laboratorio: arranque del cómputo frente a tiempo de ejecución en Microsoft Fabric

Cuando un notebook «tarda tres minutos», ese tiempo se reparte en lugares muy distintos: esperar una sesión de Spark, inicializar el primer job de Spark y ejecutar de verdad tu código. Tienen causas y soluciones distintas, y solo algunas se pueden medir desde dentro del notebook. Este laboratorio las separa con JaviPerf, una biblioteca experimental, sobre datos sintéticos, y recorre la primera ejecución real en Microsoft Fabric.

1. ¿Por qué medir el arranque por separado?

Una celda solo puede ejecutarse cuando su sesión de Spark está lista, así que ninguna celda puede medir el tiempo anterior a su inicio. Todo lo que mide un notebook empieza después de que la sesión estuviera disponible. Dentro del notebook, dos efectos más distorsionan las mediciones ingenuas:

Y fuera del notebook, Fabric informa duraciones con sus propios límites: el arranque de la sesión en el panel de información de la sesión, y el tiempo transcurrido de la aplicación Spark en la monitorización, que sigue creciendo mientras la sesión está abierta. Miden cosas distintas y nunca se suman.

  1. Empieza el arranqueRun all seleccionadoInvisible para todas las celdas
  2. Lo informa FabricSesión listaSession information, duración de arranque
  3. Reloj del notebookPrimera celda de códigoCota superior de la disponibilidad
  4. JaviPerfPrimera acción de SparkIncluye costes únicos
  5. JaviPerfDefinir la transformaciónDiferida, sin job de Spark
  6. JaviPerfMaterializarUna acción procesa los datos
  7. JaviPerfInformeFuentes y relojes etiquetados
Una ejecución del notebook y quién puede medir cada parte. El arranque termina antes de que pueda ejecutarse ninguna celda: lo informa Fabric o una persona, no el notebook. El notebook mide todo lo que ocurre desde su primera celda. Estas duraciones nunca se suman.
Fase Quién la mide Por qué
Arranque de la sesión El panel View session information de Fabric; o tú, con un reloj (hoja de registro); opcionalmente un JSON de sesión Livy Ninguna celda puede ejecutarse antes de que la sesión esté lista
Primera acción de Spark El notebook El primer job paga costes únicos que los siguientes no pagan
Definir frente a materializar El notebook, con recuento de jobs de Spark Las transformaciones son diferidas: definirlas no hace trabajo
UDF de Python frente a funciones integradas El notebook, con comprobación de salidas Solo se compara si ambas versiones devuelven las mismas filas
Observaciones del plan El notebook (no se ejecuta ningún job) Estáticas: lo que contiene el plan, no cuánto tardó

Una sesión reutilizada (una sesión interactiva existente o una sesión compartida de alta simultaneidad) no tiene arranque en esa ejecución: JaviPerf lo indica como no aplicable, nunca como cero. Un valor que falta es no disponible, nunca cero.

Requisitos previos

Crear el wheel actual en local

La instalación editable y la compilación solo afectan al entorno de desarrollo local. Desde la raíz del repositorio:

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

Los metadatos actuales de libraries/javiperf/pyproject.toml generan .codex-artifacts/private-wheels/javiperf-0.2.1-py3-none-any.whl. La compilación no lo carga. Para repetir los pasos del Environment con 0.2.1, carga ese archivo creado en local. Las pruebas de esta página documentan la ejecución anterior con 0.2.0; el enlace de descarga solo sirve una copia de ese wheel histórico desde el servidor de desarrollo. Los informes de duración de 0.2.1 aún no se han ejecutado en Fabric.

Descargar el wheel histórico

El enlace solo funciona en el servidor de desarrollo local, a través de localhost. Sirve el wheel de JaviPerf 0.2.0 que se usó en la ejecución real, compilado con python -m build --wheel --outdir .codex-artifacts/private-wheels libraries/javiperf. JaviPerf no está publicado en PyPI, y el wheel nunca forma parte del sitio público.

2. Instalar varias bibliotecas en un mismo Environment

La ejecución real reutilizó el Environment del laboratorio de JaviMapper, env_javimapper_lab, en lugar de crear uno nuevo. Un Environment puede contener varias bibliotecas personalizadas, así que un único Environment publicado puede servir a los notebooks de ambos laboratorios.

  1. Abre env_javimapper_lab (o crea un Environment en Runtime 2.0 si no tienes uno).
  2. Selecciona Custom libraries y la pestaña Full mode.
  3. Mantén JaviMapper instalado. No lo quites ni lo vuelvas a cargar.
  4. Carga (Upload) javiperf-0.2.0-py3-none-any.whl.
  5. Guarda: el wheel aparece como Saved y New, y el panel Pending changes lo muestra.
  6. Selecciona Publish all y espera.
  7. Comprueba que los dos wheels muestran Success.

Reutilizar el Environment ahorra una segunda publicación y mantiene ambos laboratorios en el mismo runtime. También los acopla: cada notebook asociado al Environment carga las dos bibliotecas, y una versión futura de cualquiera de ellas podría declarar una dependencia que entre en conflicto con la otra. El núcleo de JaviPerf no tiene dependencias de terceros, lo que reduce ese riesgo aquí, pero revisa el resultado de la publicación tras cada actualización en lugar de dar por hecha la compatibilidad. Microsoft documenta que las bibliotecas en modo Full se instalan al iniciar una sesión y pueden alargar el arranque; la sección 7 muestra lo que informó una ejecución.

3. Importar el notebook

Importa labs/javiperf-fabric-performance-lab/notebooks/javiperf-fabric-performance-lab.ipynb desde tu copia del repositorio (Import notebook en el workspace). En la barra del notebook, selecciona el Environment publicado (env_javimapper_lab en la ejecución real). Después puedes comprobar la instalación en una celda nueva: import javiperf; print(javiperf.__version__) muestra 0.2.0.

El notebook usa EXECUTION_MODE = "fabric" por defecto y la sesión spark que proporciona Fabric. Sus 18 celdas se muestran al final de esta página tal como están guardadas en el repositorio, con salidas de una ejecución local.

4. Asociar el Lakehouse

Crea un lakehouse para el laboratorio (lh_javiperf_lab en la ejecución real) y añádelo al notebook como predeterminado. El laboratorio genera sus propios datos sintéticos, así que no necesita tablas Delta ni archivos CSV de entrada. El lakehouse solo es donde se escribe el informe HTML: Files/javiperf-lab/output/javiperf-lab-report.html.

5. Ejecutar el experimento

Selecciona Run all. La celda de parámetros mantiene la carga por defecto, ROWS = 200_000 filas sintéticas, con REPEAT = 3 ejecuciones medidas por versión. Después, los ejercicios:

  1. Primera acción de Spark. spark.range(1).count() no lee datos; se mide y luego se repite para mostrar qué parte era un coste único.
  2. Transformación diferida. Se mide la definición de una agregación junto con el recuento de jobs de Spark: cero.
  3. Ejecución materializada. El escritor noop ejecuta el plan completo sin escribir nada; ahora sí hay jobs.
  4. UDF de Python frente a funciones integradas. La misma limpieza, como UDF de Python y con upper(trim(...)), ejecutadas alternativamente tras un calentamiento, comprobando fuera de la región medida que las salidas son iguales.
  5. Análisis del plan. Observaciones estáticas a partir de explain(): no se ejecuta ningún job.
  6. Informe. Un único archivo HTML autónomo, mostrado en el notebook y guardado en el lakehouse.

Notebook: javiperf-fabric-performance-lab.ipynb

PySpark notebookCeldas mostradas 7, 8, 9, 10 de 18Abrir el notebook completo

Vista de solo lectura del archivo del notebook. Nada en esta página ejecuta código.

  1. Celda 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. Celda 8PySparkEjercicio 2: la primera acción de Spark9 líneas
    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)

    Salida

    first action: 4.801 s (2 Spark job(s)); same action again: 0.317 s
  3. Celda 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. Celda 10PySparkEjercicio 3: definir frente a materializar15 líneas
    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)")

    Salida

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

No se muestran aquí: celdas 1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18. Abrir el notebook completo (las 18 celdas, en orden)

Notebook: javiperf-fabric-performance-lab.ipynb

PySpark notebookCeldas mostradas 11, 12, 13, 14 de 18Abrir el notebook completo

Vista de solo lectura del archivo del notebook. Nada en esta página ejecuta código.

  1. Celda 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. Celda 12PySparkEjercicio 4: UDF frente a funciones integradas17 líneas
    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")

    Salida

    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. Celda 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. Celda 14PySparkEjercicio 5: observaciones del plan10 líneas
    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]}")

    Salida

    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.

No se muestran aquí: celdas 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18. Abrir el notebook completo (las 18 celdas, en orden)

Las salidas anteriores proceden de una ejecución local de PySpark en un equipo de desarrollo, no de Fabric: muestran la forma de los resultados, no el rendimiento en Fabric. Las salidas de estas celdas en la ejecución real no se guardaron, así que esta página no da ninguna cifra de Fabric para la primera acción, el ejercicio de evaluación diferida ni la comparación de UDF.

Lee el veredicto de una comparación junto con su comprobación de salidas: una versión más rápida que devuelve filas distintas no es una mejora.

6. Encontrar la información de la sesión

El notebook no puede ver su propio arranque, pero Fabric lo informa. En la ejecución real, estaba aquí:

  1. Vuelve al notebook (con su sesión aún en marcha).
  2. En la barra de herramientas, abre la flecha junto a Standard session.
  3. Selecciona View session information.
  4. En el panel, busca Startup details.
  5. Lee Startup duration y Delay reason(s). Anota también Session source y Runtime version.

Copia solo esos valores. El Session ID del panel y su JSON de Diagnostics contienen identificadores (de sesión, notebook y workspace) y no deben ir en una hoja de registro de laboratorio ni en un informe compartido. La etiqueta Diagnostics al pie de la página de monitorización de la aplicación Spark no se podía pulsar en esta ejecución: usa el menú de sesión del notebook.

La hoja de registro y el notebook del laboratorio se escribieron antes de la ejecución real y hablan de Session Details (Session Start Insights). En esta ejecución, los detalles de arranque estaban en el panel View session information descrito arriba.

7. Interpretar el resultado del arranque

Lo que dice este único valor, y lo que no:

Por qué sigue siendo útil: es una cifra real y con fuente para la parte de una ejecución que ningún notebook puede medir, y muestra dónde leerla. Para sacar conclusiones hacen falta varias sesiones nuevas, idealmente frente a un Environment sin las bibliotecas personalizadas.

Anótalo. Copia los valores en la hoja de registro tal como se muestran, con las horas de solicitud y de disponibilidad en blanco (no las anotaste):

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 (solo local, aún no ejecutado en Fabric) lee las tres últimas columnas como una observación solo de duración: conserva 28,843 s con su fuente, nunca inventa marcas de tiempo a partir de ella y nunca la suma a los tiempos del notebook. El wheel 0.2.0 usado en la ejecución real ignora esas columnas.

8. Leer la monitorización de la aplicación Spark

La página de monitorización de la aplicación Spark (abre la ejecución del notebook desde Monitor) muestra los jobs de Spark de la sesión y los detalles de su ejecución.

En la captura, los jobs 6 a 22 habían terminado correctamente, con duraciones de 42 ms a 2 sec 226 ms, y los detalles mostraban una duración total y en ejecución de 3 min 52 sec con 0 sec en cola, mientras la aplicación seguía Running.

  • Arranque de la sesiónSession information de Fabric
    1. Cómputo solicitado
    2. Sesión lista
  • Aplicación SparkMonitorización, total y en ejecución
    1. La aplicación empieza
    2. Todos los jobs de la sesión
    3. Sigue activa mientras está abierta
  • Un job de SparkMonitorización, pestaña Jobs
    1. Job enviado
    2. Job terminado
  • Fase de JaviPerfReloj del notebook
    1. La fase empieza en una celda
    2. La fase termina en una celda
Cuatro duraciones, cuatro límites distintos. Cada duración empieza y termina en puntos distintos, y algunas se solapan. Se leen en paralelo; sumarlas contaría el mismo tiempo dos veces.

9. Entender el informe de JaviPerf

El informe es un único archivo HTML sin scripts ni recursos externos, mostrado con displayHTML y guardado en Files/javiperf-lab/output/javiperf-lab-report.html.

En la ejecución real, la tabla Session start del informe mostraba Startup (request to ready): unavailable, con sus marcas de tiempo not recorded. Era correcto: cuando se ejecutó el notebook no se había introducido ninguna observación del arranque, y JaviPerf indica un valor que falta como no disponible, nunca como cero. El valor de 28,843 segundos se leyó después en el panel de información de la sesión. El informe de esa ejecución se conserva tal cual; no se reescribe para incluir un valor que no tenía.

Lo que contiene el informe y lo que aportó esta ejecución:

Parte En la ejecución real
Arranque de la sesión No disponible al generar el informe; Fabric informó después 28,843 s (sección 7)
Fases medidas y comparación de UDF frente a funciones integradas Generadas en Fabric, pero los valores no se capturaron; esta página no da ninguno
Observaciones del plan Visibles: por ejemplo, PYTHON_UDF (un operador BatchEvalPython) en el plan de la versión con UDF
Investigaciones por validar Hipótesis a partir de los planes, como comprobar si una función integrada puede sustituir a la UDF
Limitaciones Siempre incluidas: los tiempos describen solo esta sesión, y una ejecución más rápida no implica menor coste

Las observaciones del plan son estáticas: describen lo que contiene un plan, no cuánto tardó ni si es un problema.

10. Conclusión y próximos experimentos

Lo que demostró la primera ejecución real:

Lo que no demostró: ninguna diferencia de rendimiento, ningún efecto en el coste ni la parte del arranque causada por cada biblioteca. Ninguno de estos experimentos se ha realizado todavía:

El notebook completo

Todas las celdas del notebook, tal como están guardadas en el repositorio, con sus salidas de una ejecución local:

Notebook: javiperf-fabric-performance-lab.ipynb

PySpark notebook18 celdas

Vista de solo lectura del archivo del notebook. Nada en esta página ejecuta código.

  1. Celda 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. Celda 2PySparkRun this cell first. Its start is an upper bound for when the session became ready4 líneas
    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. Celda 3PySparkParámetrosParameters15 líneas
    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. Celda 4PySparkCode32 líneas
    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")

    Salida

    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. Celda 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. Celda 6PySparkCode23 líneas
    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)

    Salida

    this run: session status unknown, startup unavailable
       The start and end timestamps of the session startup were not recorded.
  7. Celda 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. Celda 8PySparkCode9 líneas
    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)

    Salida

    first action: 4.801 s (2 Spark job(s)); same action again: 0.317 s
  9. Celda 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. Celda 10PySparkCode15 líneas
    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)")

    Salida

    define: 0.078 s, 0 Spark job(s)
    materialize: 1.993 s, 2 Spark job(s)
  11. Celda 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. Celda 12PySparkCode17 líneas
    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")

    Salida

    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. Celda 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. Celda 14PySparkCode10 líneas
    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]}")

    Salida

    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. Celda 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. Celda 16PySparkCode11 líneas
    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)

    Salida

    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. Celda 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. Celda 18PySparkCode5 líneas
    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.")

    Salida

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

Seguridad, capacidad y limpieza

Repetir la ejecución

La lista de comprobación de una ejecución real y lo que conviene capturar están en labs/javiperf-fabric-performance-lab/FABRIC_TEST_PLAN.md. Para una serie comparable, anota cada ejecución en la hoja de registro: si la sesión era nueva o reutilizada, el grupo, el Environment y su modo de publicación, y la duración de arranque y el motivo de retraso tal como se muestran.

Ruta local opcional

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

El script ejecuta cada celda en local (establece EXECUTION_MODE en local tras la celda de parámetros) y guarda las salidas. Las cifras locales solo describen tu equipo.