Skip to content

Measure where Studio's startup time actually goes - #7553

Merged
danielhanchen merged 18 commits into
mainfrom
perf/startup-profiling
Jul 29, 2026
Merged

danielhanchen merged 18 commits into
mainfrom
perf/startup-profiling

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Nothing measured this

studio/backend/main.py logs lifespan startup completed in X ms, but no test or CI job ever asserted a budget. A repo-wide grep for startup_ms or time_to_ready matches only that one file. studio_test_kit/lifecycle.py polls /healthz in a while time.time() < deadline loop and throws away the elapsed time it already computes; its default healthz_timeout_s of 180 seconds was the only recorded expectation anywhere.

What this adds

scripts/profile_startup.py breaks a launch into phases:

  • t_import -- python -X importtime in a subprocess, reporting the top cumulative contributors
  • t_spawn -- process start to first output
  • t_healthz -- spawn to /healthz 200

over N repeats, reported as median and max. .github/workflows/startup-profile-ci.yml runs it on Linux, macOS and Windows so the numbers are per platform rather than per laptop.

First numbers

On Linux, importing the backend module costs 5.7 to 6.6 seconds before the server can bind, and it dominates everything else.

That is eager module-level imports pulled in by the routes package. Worth recording that it is not the hardware detection I first assumed: utils.hardware is 23ms and does not pull torch. Guessing would have sent the optimisation work at the wrong target, which is the argument for having the measurement in the repo rather than in someone's terminal.

On the budget gate

--max-healthz-seconds exists but is deliberately not wired into a failing gate yet. A threshold picked before the per-platform numbers are agreed would either be meaningless or flaky. This PR is the measurement; the budget is a follow-up once there is data to set it from.

danielhanchen and others added 2 commits July 28, 2026 12:08
Nothing measured this. studio/backend/main.py logs 'lifespan startup completed in
X ms' but no test or CI job ever asserted a budget, a repo-wide grep for
startup_ms or time_to_ready matches only that one file, and studio_test_kit polls
/healthz in a loop that discards the elapsed time it already computes. Its
default healthz_timeout_s of 180 was the only recorded expectation.

scripts/profile_startup.py breaks a launch into phases: import cost via
python -X importtime in a subprocess (top cumulative contributors), process spawn
to first output, and spawn to /healthz 200, over N repeats with median and p90.

First numbers on Linux: importing the backend module costs 5.7 to 6.6 seconds
before the server can even bind, and it dominates everything else. That is eager
module-level imports pulled in by the routes package, not the hardware detection
I first suspected: utils.hardware is 23ms and does not pull torch.

--max-healthz-seconds exists so a budget can be enforced once per-platform
numbers are agreed. It is not wired into a gate yet, deliberately: a threshold
picked before the data is in would either be meaningless or flaky.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1341ab6d7e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +77 to +80
if [ "${{ runner.os }}" = "Windows" ]; then
pwsh -NoProfile -File ./install.ps1 2>&1 | tee logs/install.log
else
bash install.sh 2>&1 | tee logs/install.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Install the checked-out code before profiling launch

Both installer invocations omit --local, so the installers follow their default PyPI path rather than overlaying the checked-out repository. Consequently, the health and lifespan measurements exercise the released unsloth backend and will remain unchanged when a PR modifies main.py, run.py, or the routes that trigger this workflow; pass --local on both platforms so the launch profile measures the reviewed code.

Useful? React with 👍 / 👎.

Comment thread scripts/profile_startup.py Outdated
Comment on lines +142 to +144
proc.terminate()
try:
out, _ = proc.communicate(timeout = 30)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Read stdout while the process is alive

The first stdout read occurs through communicate() only after the process has been terminated, so t_first_byte can never be timestamped and every run omits the advertised spawn-to-first-output phase. Additionally, a startup that writes enough output to fill the pipe can block before reaching health because nothing drains it during polling; consume stdout concurrently and record the first-read timestamp.

Useful? React with 👍 / 👎.

Comment thread scripts/profile_startup.py Outdated
report: dict = {
"platform": platform.system().lower(),
"machine": platform.machine(),
"python": platform.python_version(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report the version of the profiled interpreter

platform.python_version() describes the controller running this script, while imports are executed by the separately supplied --python interpreter. In the workflow, the controller is the runner's python3 and the profiled interpreter is the installed Studio environment, so differing versions cause the JSON and job summary to attribute timing results to the wrong Python version; query a.python for its version instead.

Useful? React with 👍 / 👎.

Comment thread scripts/profile_startup.py Outdated
print("== import graph ==")
report["imports"] = profile_imports(a.python)
imp = report["imports"]
if imp.get("ok") or imp.get("total_seconds"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject partial import profiles after an import failure

When import main raises after importing any dependencies, -X importtime still emits rows, so profile_imports() returns ok: false together with a plausible total_seconds. This condition treats that partial timing as a successful profile, and the workflow summary also publishes it based solely on total_seconds, allowing a broken or incomplete import graph to masquerade as a valid startup result instead of surfacing the subprocess failure.

Useful? React with 👍 / 👎.

runs.append(r)
print(f" run {i + 1}: healthz={r['healthz_seconds']}s "
f"lifespan={r['lifespan_ms']}ms reached={r['reached_healthz']}")
got = [r["healthz_seconds"] for r in runs if r["healthz_seconds"] is not None]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include failed launches in budget enforcement

Filtering out every run without a health timestamp lets failed launches disappear from the aggregate: if one repeat succeeds and the others time out, the median and maximum—and therefore --max-healthz-seconds—are calculated only from the successful run, while if all repeats fail the budget path merely warns and exits successfully. A launch that never becomes healthy should make an enabled budget fail rather than making the measured result look faster.

Useful? React with 👍 / 👎.

- 'studio/backend/main.py'
- 'studio/backend/run.py'
- 'studio/backend/routes/**'
- 'studio/src-tauri/src/preflight**'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exercise Tauri before profiling preflight changes

A PR that changes the Rust preflight code triggers this workflow, but the profile only starts the Python unsloth studio --api-only CLI and never builds or launches the Tauri application. Any regression in the preflight phase is therefore invisible and produces unchanged backend timings despite the workflow claiming coverage; either add an actual Tauri startup measurement or remove this path from the trigger.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The job is continue-on-error with no budget wired, and :19 says so deliberately. Nothing passes vacuously and no published number is wrong yet, so this is a follow-up once the baseline numbers settle.

Both installer calls omitted --local, so every phase measured the published PyPI
backend and could not move when a PR edits main.py, run.py or routes. t_first_byte
was a dead local, advertised in the docstring but never returned, and the reader
could deadlock once the child filled the pipe. A failed launch and an impossible
budget both produced a warning and exit 0, and the importtime parse reported the
largest cumulative row, which is site, not main, so a raising import published a
number as success. Pin the controller to the profiled venv's interpreter.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bf9095011d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

paths:
- 'studio/backend/main.py'
- 'studio/backend/run.py'
- 'studio/backend/routes/**'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cover the full startup import graph in path filters

The workflow does not run for changes to large portions of the code it measures. For example, routes.training imports utils.models.model_config, but a PR changing studio/backend/utils/** is excluded; the same applies to other backend packages, unsloth_cli/**, and dependency changes in pyproject.toml. Such changes can add substantial eager-import or CLI launch time while producing no startup profile, defeating regression tracking unless the filter covers the complete backend/launcher dependency graph.

Useful? React with 👍 / 👎.

Comment thread scripts/profile_startup.py Outdated
return {
"ok": True,
# The largest cumulative figure is the whole graph: `import main` itself.
"total_seconds": round(by_cum[0][1] / 1e6, 3),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Select the main import row instead of the largest row

-X importtime emits independent interpreter-startup rows such as site, so the largest cumulative row is not guaranteed to be main. Once main becomes faster than one of those roots—or with a slow sitecustomize—this reports that unrelated row as import main, causing the metric to plateau or regress for reasons outside the measured import graph. Locate the row whose module name is main rather than using by_cum[0].

Useful? React with 👍 / 👎.

f" run {i + 1}: healthz={r['healthz_seconds']}s "
f"lifespan={r['lifespan_ms']}ms reached={r['reached_healthz']}"
)
got = [r["healthz_seconds"] for r in runs if r["healthz_seconds"] is not None]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not compute launch statistics only from successful runs

When any repeat times out or exits before healthz, this filters that run out and computes the median and maximum from only the survivors. The default workflow does not pass --max-healthz-seconds, and its summary displays these aggregates without failed_runs, so even two failed launches plus one fast survivor are presented as a normal fast startup measurement. Mark the aggregate invalid when a run fails or prominently include the failure count instead of silently dropping failures.

Useful? React with 👍 / 👎.

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Invoke the resolved interpreter instead of python3

On a runner where Python is available as python but not python3, the fallback immediately above correctly resolves PY to python, but this command ignores it and still invokes the missing python3, so no profile is produced. This is especially relevant to the cross-platform Windows leg; run the controller through "$PY" (and avoid the same hardcoded python3 in the summary step) so the interpreter discovery actually takes effect.

Useful? React with 👍 / 👎.

# run.py or routes/**. --local overlays the checkout editable, and
# pyproject ships studio.backend*, so the profiled server is this diff.
if [ "${{ runner.os }}" = "Windows" ]; then
pwsh -NoProfile -File ./install.ps1 --local 2>&1 | tee logs/install.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pin the dependency used by the startup benchmark

In this repository, install.sh --local and install.ps1 --local also reinstall unsloth-zoo directly from its unpinned Git main branch. Since the profile identifies unsloth_zoo as a major startup contributor, two runs of the same reviewed commit can record different import and health timings solely because that external branch moved, making the resulting time series unsuitable for detecting regressions in this checkout. Pin the zoo revision used by the profiling job while retaining the editable overlay for this repository.

Useful? React with 👍 / 👎.

--python "$PY" \
${BIN:+--bin "$BIN"} \
--repeats "${{ inputs.repeats || '3' }}" \
--json "startup-${{ matrix.os }}.json" 2>&1 | tee logs/profile.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve profiler failures through the tee pipeline

This step does not enable pipefail, so if profile_startup.py crashes, times out, or exits nonzero, the pipeline takes tee's successful status and the profile step is reported as successful. The always-running summary then treats the missing JSON as a benign “no profile produced,” hiding the failure that prevented this workflow from collecting any measurement. Enable set -o pipefail here as the install step already does.

Useful? React with 👍 / 👎.

The aggregates cover only the runs that reached healthz, so two dead launches
and one fast one rendered as a normal fast startup, and an all-failed phase
printed nothing at all. With continue-on-error and no budget wired, that summary
is the only thing anyone sees. Say how many launches the number is made of, and
say so explicitly when none came up.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 64993a6285

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +237 to +241
ap.add_argument(
"--repeats",
type = int,
default = 1,
help = "launch repeats; the median is reported (imports are measured once)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require at least one launch repeat

When --repeats is zero or negative—values accepted directly from the workflow-dispatch string—range(a.repeats) performs no launches, yet the script writes a successful-looking report with an empty runs list and no launch result; the summary then prints no launch status at all. If a health budget is supplied, this also reaches the “not enforcing” warning and exits 0. Reject values below 1 during argument parsing so an invalid benchmark request cannot silently produce no measurement.

Useful? React with 👍 / 👎.

"runs": runs,
"failed_runs": sum(1 for r in runs if not r["reached_healthz"]),
"healthz_median_seconds": round(statistics.median(got), 3) if got else None,
"healthz_max_seconds": round(max(got), 3) if got else None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report the promised p90 instead of the maximum

For repeated launches, this stores the single slowest observation even though the change promises median and p90 results. A maximum is much more sensitive to one-off runner noise and changes systematically with the requested repeat count, so dispatch runs with different --repeats values do not produce the advertised comparable tail-latency statistic; compute and publish an actual p90 rather than substituting max(got).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right about the artifact, so I fixed the PR body rather than the code: it now says median and max. The code is already honest, the field is healthz_max_seconds (profile_startup.py:305) and the summary prints "...s max" (startup-profile-ci.yml:138); p90 appears nowhere in the tree. At the default --repeats 3 p90 and max coincide anyway, so there is nothing to compute differently.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 64993a6285

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +27 to +30
- 'studio/backend/main.py'
- 'studio/backend/run.py'
- 'studio/backend/routes/**'
- 'studio/src-tauri/src/preflight**'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Trigger profiling for all startup dependencies

When a PR changes an eagerly imported backend module outside these two files and routes/**, this workflow does not run; for example, main.py directly imports auth, core, loggers, and numerous utils modules, while changes under unsloth_cli/** can also affect the measured process-to-health time. Consequently, regressions in much of the actual startup graph bypass the new measurement entirely. Broaden the filter to cover the backend and CLI startup trees, such as studio/backend/** and unsloth_cli/**.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. main.py imports at module scope from utils (199, 215, 335-351), auth (333-334), loggers (654-655), hub (319-330), picker (324) and core (1000), and routes/models.py:20,65 pulls in utils.utils and utils.hidden_models, so most of the measured graph sat outside the filter. Broadened to studio/backend/** (minus tests) plus unsloth_cli/**, since the launch phase spawns unsloth studio --api-only.

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use the resolved Python command on Windows

On Windows runners where Python is exposed as python.exe rather than python3, this hardcoded invocation fails before profiling begins. The immediately preceding fallback explicitly resolves either python3 or python, but that value is used only for --python; the driver and the Summary step still invoke python3 directly. Use the resolved interpreter to run the script and likewise avoid hardcoding python3 in the summary so the Windows matrix entry can produce a profile.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked against a real run: in run 30372438698 the windows-latest job finished green, with python3 scripts/profile_startup.py reporting import main: 17.507s and three healthy launches, and the Summary step's python3 - "$f" heredoc also succeeded. Git Bash on windows-latest resolves python3, so line 100 is not a failure mode. The fallback on line 99 is for --python, where the venv interpreter is the point.

Comment on lines +163 to +165
with urllib.request.urlopen(url, timeout = 2) as r:
if r.status == 200:
t_healthz = time.perf_counter() - t0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the health payload before recording readiness

When the selected port returns any HTTP 200 with malformed or non-Unsloth content, this loop records the backend as ready and terminates it even though the desktop launcher would reject that response. Checked studio/src-tauri/src/process.rs: generic_backend_health_ok parses the JSON and requires status to be alive/healthy and service to equal Unsloth UI Backend; the preflight probe applies similar checks. Mirror that predicate here so endpoint regressions or a port race cannot produce a falsely fast successful launch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The port comes from _free_port() at line 299, bound on 127.0.0.1 immediately before the spawn, so the only responder is our own child. A regressed or removed /api/health returns 404 from FastAPI, not a 200 with wrong content, so there is no realistic path to a false ready here. This measures time to first 200 on our own port; the launcher's identity checks in process.rs guard adoption of a sibling install, which is a different problem.

Comment on lines +238 to +240
"--repeats",
type = int,
default = 1,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject non-positive repeat counts

If the CLI or workflow-dispatch input supplies --repeats 0 or a negative value, range(a.repeats) performs no launches, the report contains an empty run list, the Summary prints no launch result, and even a configured health budget exits successfully with only a warning. Since --import-only already represents an intentional no-launch run, validate this argument as a positive integer so an invalid experiment cannot silently produce no measurement.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and already fixed on this branch: profile_startup.py:264-265 now calls ap.error("--repeats must be at least 1") right after parse_args. Without it --repeats 0 ran no launches and --max-healthz-seconds still exited 0 on the "no healthz measurement" warning path, so the gate asserted nothing.

range(0) launches nothing, so the empty runs list reached the budget check as
"no healthz measurement", warned and exited 0: a gate that cannot fail. The
value comes straight from a dispatch input, so reject it loudly instead.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8b7649d5f6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use the detected Python executable on Windows

On Windows runners where Python is exposed as python rather than python3, this command fails before producing a profile even though the preceding line successfully detects an available interpreter. The repository's cross-platform release workflow explicitly falls back from python3 to python for its Windows matrix, but this step and the Summary step both hard-code python3; invoke the detected executable in both places so the advertised Windows profile actually runs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the other note on line 100, and disproved by run 30372438698: the windows-latest job ran python3 scripts/profile_startup.py and the python3 Summary heredoc, both success, producing import 17.507s and healthz 8.29-8.68s. release-desktop.yml:515 hedges, but it is not evidence that python3 is missing here.

--python "$PY" \
${BIN:+--bin "$BIN"} \
--repeats "${{ inputs.repeats || '3' }}" \
--json "startup-${{ matrix.os }}.json" 2>&1 | tee logs/profile.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate profiler failures through the tee pipeline

If profile_startup.py crashes—for example because the installed interpreter or CLI cannot be executed—the pipeline still returns tee's successful status because this step never enables pipefail. Unlike the Install Studio step, which explicitly sets it, this makes a broken profiling run appear successful and leaves only a quiet “no profile produced” summary; enable pipeline failure propagation here so the step records the failure even if the job remains intentionally non-blocking.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The step declares shell: bash (line 90), which GitHub runs as bash --noprofile --norc -eo pipefail {0}, so pipefail is already on and a profiler crash already fails the step. The explicit set -o pipefail in Install Studio is redundant rather than a missing safeguard here.

Comment on lines +27 to +29
- 'studio/backend/main.py'
- 'studio/backend/run.py'
- 'studio/backend/routes/**'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Trigger profiling for all backend startup dependencies

The path filter omits backend modules imported by main.py and routes, such as studio/backend/utils/**, so a PR can substantially change the measured import graph without running this workflow at all. For example, routes/models.py imports utils.utils and utils.hidden_models at module scope, yet edits to either are outside these paths; broaden the backend filter so the startup profiler runs when transitive startup code changes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, same gap as the other path-filter note. routes/models.py:20 and :65 import utils.utils and utils.hidden_models at module scope, and main.py:335-351 imports utils.hardware, utils.cache_cleanup and utils.update_status. The filter now covers studio/backend/** (excluding tests) and unsloth_cli/**.

Comment on lines +186 to +188
m = re.search(r"lifespan startup completed in ([\d.]+)ms", line)
if m:
lifespan_ms = float(m.group(1))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Parse the structured lifespan log output

With the backend's default production logging configuration, JSONRenderer receives the event as "lifespan startup completed in %.1fms" and the numeric argument separately in positional_args, because the configured processor chain has no positional-argument formatter. Consequently this regex never matches the emitted line and every run reports lifespan_ms: null, silently eliminating one of the four phases the profiler promises to measure; parse the structured event and argument or otherwise obtain the formatted duration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make_filtering_bound_logger interpolates event % args before the processor chain, so the renderer only ever sees the finished string. Reproduced on structlog 26.1.0: JSONRenderer emits {"event": "lifespan startup completed in 1089.4ms", ...} and ConsoleRenderer the plain text; the regex on line 186 matches both. Run 30372438698 confirms it in CI, windows-latest reporting lifespan=749.9ms, 415.4ms, 352.7ms.

The path filter listed main.py, run.py and routes/**, but the graph the
profiler measures is far wider: main.py imports auth, core, hub, loggers,
models, picker and utils at module scope, and routes/models.py imports
utils.utils and utils.hidden_models. A change to any of those moved
`import main` without ever running this job, so the regressions the
workflow exists to catch went unmeasured.

Cover studio/backend/** (tests excluded) and unsloth_cli/**, since the
launch phase spawns `unsloth studio --api-only` and the CLI is on the
process-to-healthz path.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4215e3a3f8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Run the profiler with the detected Python executable

On the Windows matrix leg, or any runner exposing only python.exe, line 106 correctly falls back from python3 to python and stores the result in PY, but this line still invokes the potentially nonexistent python3; the Summary step repeats the same hardcoded invocation at line 119. Since this job does not run actions/setup-python and installer PATH changes cannot propagate back into the Bash step, the profiling command can fail before producing JSON, leaving the Windows experiment with only logs because the job is allowed to continue.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third time on the same site: this is the same line 107 and the same Summary heredoc at :119 already answered on 3668528736 and 3668689399. The Profile and Summary steps are byte identical to the green windows-latest job in run 30372438698 (only the path filter block changed since; git diff 64993a6 -> HEAD touches nothing below :39), and that job ran python3 scripts/profile_startup.py to completion, reported import main: 17.507s and rendered the python3 heredoc summary. Also note :106 is a last-resort branch that does not even fire on Windows, since the venv supplies Scripts/python.exe at :105, so its existence is not evidence that python3 is missing.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4215e3a3f8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the portable Python command on Windows

On windows-latest configurations where Git Bash exposes python.exe but no python3 shim, this command fails before producing the JSON report; the summary repeats the unconditional python3 invocation, and the job's continue-on-error then leaves the Windows leg with no measurements. The workflow already resolves a portable interpreter into PY above, and the existing Windows-capable release workflow similarly falls back from python3 to python, so invoke the profiler and summary through a resolved interpreter instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the fourth report of this same line. Run 30372438698 executed this exact python3 scripts/profile_startup.py invocation on windows-latest and finished green, reporting import main: 17.507s, and the Summary step's python3 heredoc ran in the same job. Line 106 is also a last-resort branch that never fires on Windows, because line 105 already resolves the venv's Scripts/python.exe, and the venv interpreter is passed explicitly via --python rather than being the one that runs the script.

Comment on lines +38 to +39
- 'scripts/profile_startup.py'
- '.github/workflows/startup-profile-ci.yml'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Trigger profiling for dependency metadata changes

The installed import graph is also controlled by the root pyproject.toml, which declares and pins measured contributors such as transformers and unsloth_zoo and is consumed by the --local installation. A dependency-only change there can substantially alter import main and launch time without matching any current path, so this workflow will not collect the regression it was added to observe; include the package/dependency metadata in the path filter.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The workflow installs with --local, and that path overlays the checkout as uv pip install -e "$_REPO_ROOT" --no-deps (install.sh:3990); the resolved dependency set comes from the literal specs at install.sh:3988 plus the published unsloth metadata, never from this repo's pyproject.toml. A dependency-only edit to pyproject.toml therefore does not change a single version in the profiled venv, so adding it to the filter would run the job on changes it cannot measure. The one dependency manifest that does drive this install, studio/backend/requirements/no-torch-runtime.txt (install.sh:2323), already matches the studio/backend/** pattern.

--python "$PY" \
${BIN:+--bin "$BIN"} \
--repeats "${{ inputs.repeats || '3' }}" \
--json "startup-${{ matrix.os }}.json" 2>&1 | tee logs/profile.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the profiler's exit status through tee

When the profiler exits nonzero—for example when a dispatch supplies repeats=0, which the script explicitly rejects—the pipeline reports tee's successful exit status because this step never enables pipefail. The summary then treats the missing JSON as a normal no-profile case, so even profiler crashes are not surfaced as failed steps and the advertised future health budget could not enforce anything through this command; enable pipefail before running the pipeline.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second report of this one. The step declares shell: bash at line 97, which GitHub runs as bash --noprofile --norc -eo pipefail {0}, so pipefail is already enabled and a nonzero profiler exit propagates through tee and fails the step.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4215e3a3f8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +91 to +93
pwsh -NoProfile -File ./install.ps1 --local 2>&1 | tee logs/install.log
else
bash install.sh --local 2>&1 | tee logs/install.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pin the dependency set used by the profile

When unsloth-zoo changes between workflow runs, these timings can move even if the reviewed backend is unchanged: both install.sh --local and install.ps1 --local forcibly reinstall unsloth-zoo from the moving Git main branch (install.sh:3742-3745, install.ps1:2399-2400), and the workflow itself identifies that package as a major import-time contributor. Pinning that overlay (and recording the revision) is necessary for results from different PRs or dates to be comparable rather than attributing upstream changes to the current diff.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The premise is right about install.sh:3742-3745 and install.ps1:2399-2400, but drift cannot break anything here. The only nonzero exit in scripts/profile_startup.py is the block at :321-342, guarded by if a.max_healthz_seconds is not None, and the workflow never passes that flag (:107-111), so the script always exits 0; the job is also continue-on-error: true (:59), and :19-20 states the budget is deliberately not a gate until it is set from observed numbers. Pinning zoo alone would not buy comparability either, since torch at ~1.9s self is the bigger contributor per :15 and floats too, along with the PyPI unsloth floor, transformers and runner hardware; the installers expose no zoo-ref knob, so pinning means patching install.sh and profiling a stack no --local user actually gets. If attribution ever matters, the cheap answer is recording unsloth_zoo-*.dist-info/direct_url.json's commit_id, which is a follow-up rather than a blocker.

Comment on lines +107 to +111
python3 scripts/profile_startup.py \
--python "$PY" \
${BIN:+--bin "$BIN"} \
--repeats "${{ inputs.repeats || '3' }}" \
--json "startup-${{ matrix.os }}.json" 2>&1 | tee logs/profile.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the profiler's exit status through tee

When the profiler exits nonzero—for example, a manual dispatch supplies repeats=0, or the health budget is later enabled and exceeded—this pipeline still returns tee's successful status because this step never enables pipefail. Bash's help set documents that pipefail makes a pipeline return the last nonzero status; without it, the failed profiler is presented as a successful profile step and may only leave the summary saying that no profile was produced.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Third occurrence of the tee claim; rejected on 3668689405 and 3670011166. Re-checked against the current file: the step still declares shell: bash at startup-profile-ci.yml:97, and GitHub runs that as bash --noprofile --norc -eo pipefail {0}, so pipefail is already enabled for this pipeline and a nonzero profiler status does propagate through tee.

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Invoke the interpreter that was actually found on Windows

On Windows runners where Python is exposed as python.exe rather than python3, this command fails before producing a profile. The preceding fallback explicitly finds the installed venv's Scripts/python.exe (or falls back to python) and stores it in PY, but the workflow ignores that result and invokes python3 unconditionally here; the Summary step does the same at line 119. Use the discovered interpreter, or install and invoke a known controller Python, so the Windows matrix leg can run.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fifth occurrence of the Windows-python claim; rejected on 3668528736, 3668689399, 3668919485 and 3670011161. Run 30372438698's startup windows-latest job concluded success running python3 scripts/profile_startup.py, reporting import main: 17.507s, and the python3 heredoc in the Summary step ran there too. Line 106 is a last resort that never fires on Windows because 105 already resolves Scripts/python.exe, and that venv interpreter is handed to the profiler via --python at line 108 rather than being the interpreter that runs the script.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4215e3a3f8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/profile_startup.py Outdated
break
time.sleep(0.25)
finally:
proc.terminate()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Kill the Windows launcher process tree

On the windows-latest matrix entry, the workflow passes Scripts/unsloth.exe, whose console-script launcher starts the Python backend as a child process. proc.terminate() stops only that launcher, leaving the backend running and retaining the stdout pipe; consequently each repeat leaks a server, reader.join(timeout=10) waits the full timeout, and later repeats share the Studio home with those orphaned processes. Use Windows process-tree termination such as taskkill /PID <pid> /T /F (as the repository's other server cleanup paths do) before reaping the launcher.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 400bc38. Scripts/unsloth.exe is a distlib launcher stub that CreateProcess-es the venv python on the zip appended to itself and waits, so the old proc.terminate() at line 173 reaped only the stub and left the backend holding the inherited stdout handle: the reader thread never sees EOF and burns the full reader.join(timeout=10), and with --repeats each iteration strands another server on the shared UNSLOTH_STUDIO_HOME. profile_launch now calls a _terminate_tree helper that runs taskkill /PID <pid> /T /F on os.name == "nt" and falls back to terminate() elsewhere, matching unsloth_cli/commands/start.py and unsloth/dataprep/synthetic.py. Verified both branches: POSIX exits -15, the nt branch issues the taskkill argv, and it is a no-op once the process is already gone.

Comment thread scripts/profile_startup.py Outdated
Comment on lines +109 to +110
# The largest cumulative figure is the whole graph: `import main` itself.
"total_seconds": round(by_cum[0][1] / 1e6, 3),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Read the cumulative time from the main row

-X importtime also emits interpreter-startup rows such as site, which are outside the import main graph. If one of those rows is slower than main—for example after backend imports are optimized or when the selected interpreter has an expensive sitecustomize—taking by_cum[0] reports that unrelated startup cost as import main and makes the profile plateau at a false value. Select the successful row whose module name is main for total_seconds, while retaining the global sort only for the contributor table.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct in mechanism, fixed in 400bc38. Reproduced it: with a trivial main, the old by_cum[0] at line 110 reported site at 0.027s as import main while main itself cost 0.000249s, because -X importtime also prints the interpreter startup graph (site, encodings, sitecustomize) which sits outside the import main subtree and is not ordered against it by construction. profile_imports now reads the row named main for total_seconds and keeps the global sort for the contributor table only. Published figures are unaffected: run 30372438698 artifacts have top_cumulative[0] = main at exactly total_seconds (windows 17.507s, ubuntu 11.349s), and a local end-to-end run reports import main 8.588s with main as the top row.

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Invoke an interpreter that exists on the Windows runner

The windows-latest job does not run actions/setup-python, and the Windows Python installations expose python.exe rather than a python3 command; the repository's other Windows workflows consistently invoke python for this reason. Thus this line fails before the profiler starts even though the preceding code has already resolved the installed venv interpreter into PY, so the workflow never produces Windows startup data. Invoke "$PY" (or explicitly set up and invoke python) for the controller and use the same available interpreter in the Summary step.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disproved by CI, sixth time this has been raised (3668528736, 3668689399, 3668919485, 3670011161, 3670135405). Run 30372438698 job startup windows-latest concluded success running exactly this line 107 python3 scripts/profile_startup.py and reported import main: 17.507s, and the Summary step heredoc, also python3, ran and uploaded startup-windows-latest.json. GitHub-hosted windows-latest ships Git for Windows plus the hostedtoolcache Python, both of which put a python3 on PATH. Line 106 is only a last resort and never fires on Windows since line 105 already resolves Scripts/python.exe, and $PY is passed via --python to profile the venv interpreter rather than to run the controller.

--python "$PY" \
${BIN:+--bin "$BIN"} \
--repeats "${{ inputs.repeats || '3' }}" \
--json "startup-${{ matrix.os }}.json" 2>&1 | tee logs/profile.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate profiler failures through the tee pipeline

In the Profile startup step, any nonzero exit from profile_startup.py is replaced by tee's successful status because this shell block does not enable pipefail (unlike the Install Studio block). A crash, invalid dispatch input, or future --max-healthz-seconds violation therefore leaves the profile step green; when no JSON was written, the always-running Summary also exits successfully after printing only no profile produced. Enable set -o pipefail in this step so the job's existing continue-on-error policy can allow but still visibly record the actual profiling failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pipefail is already on, fourth time this has been raised (3668689405, 3670011166, 3670135401). The Profile startup step declares shell: bash at line 97, which GitHub runs as bash --noprofile --norc -eo pipefail {0}, so the | tee logs/profile.log on line 111 already propagates a nonzero exit from profile_startup.py. That is why the Install Studio block needs no extra set -o pipefail either. Confirmed --repeats 0 still exits 2 through this same pipeline.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction to the last sentence of my reply: the Install Studio block does carry an explicit set -o pipefail at line 82, but it is redundant for the same reason, since that step also declares shell: bash at line 78. The asymmetry between the two blocks is cosmetic, not behavioural; both already run under -eo pipefail.

shimmyshimmer and others added 2 commits July 29, 2026 01:25
total_seconds took by_cum[0], the largest cumulative row in -X importtime
output. That output also carries the interpreter's own startup graph (site,
encodings, whatever a venv sitecustomize pulls in), which is not part of
import main, and the two are not ordered by construction. With a trivial main
the old code reported site's 0.027s as "import main" while main actually cost
0.000249s. Today's backend dwarfs site so the published figures are unchanged,
but the headline number must not silently become another module's cost once
the backend imports get optimized, so read the row named main.

profile_launch spawned Scripts/unsloth.exe on Windows. A pip console-script
.exe is a distlib launcher stub that CreateProcess's the venv python and waits,
so terminate() reaped the stub and left the backend holding the inherited
stdout handle: the reader thread never saw EOF and burned the full 10s join,
and with --repeats each iteration stranded another server on the shared
UNSLOTH_STUDIO_HOME. Walk the tree with taskkill /T, matching the cleanup in
unsloth_cli/commands/start.py and unsloth/dataprep/synthetic.py.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 51d9ccb244

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +36 to +39
- 'unsloth_cli/**'
- 'studio/src-tauri/src/preflight**'
- 'scripts/profile_startup.py'
- '.github/workflows/startup-profile-ci.yml'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run profiling when installation inputs change

A PR that changes only pyproject.toml, install.sh, or install.ps1 will not trigger this workflow, even though the install step consumes those files and their dependency/interpreter selection determines what is profiled. Such changes can alter both import and launch timing while producing no startup profile, so include the root package and installer inputs in pull_request.paths.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair, and the mechanism is stronger than the dependency-table angle I turned down on 3670011164. install.sh --local is what the job profiles, and the installers choose the venv interpreter itself (install.sh:1759-1761 picks 3.12 or 3.13, install.ps1:169 the same), which moves import main directly; pyproject.toml:73 is what makes --local overlay studio.backend* at all, so an edit there decides whether the profiled server is the diff or the published release. Added install.sh, install.ps1 and pyproject.toml to the filter. The earlier note still stands for the narrow case it made: a dependency-only pyproject edit is not resolved, since the overlay is uv pip install -e . --no-deps.

Comment thread scripts/profile_startup.py Outdated
Comment on lines +378 to +379
if med is None:
print("::warning::no healthz measurement; not enforcing the budget")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fail a requested budget when no launch was measured

When --max-healthz-seconds is requested but the CLI cannot be found (or launch is otherwise skipped), med is None, failed_runs is zero, and this branch returns success after only a warning. A CI job using this option therefore passes without making any health request, so the budget should fail closed whenever no launch measurement exists.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and vacuous exactly as described: with --max-healthz-seconds set and no CLI found, report["launch"] was {"skipped": ...}, so failed_runs was 0, med was None, and the branch printed ::warning::no healthz measurement and fell through to return 0. A budget that never issued a health request reported success. Fixed in 1d436af: that branch now prints ::error:: naming the skip reason and returns 1. Also closed the sibling hole at parse time, since --import-only --max-healthz-seconds X never launches anything either, so it now exits 2 rather than "passing" the budget. Regression test in tests/test_profile_startup_gate.py::test_budget_fails_when_no_launch_was_measured, which returns 0 against the pre-fix script.

Comment thread scripts/profile_startup.py Outdated
Comment on lines +154 to +156
check = False,
)
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back when taskkill reports failure

On Windows, taskkill can complete with a nonzero status without raising because check=False, but this unconditional return still skips proc.terminate(). If that happens while the launcher remains alive, the later timeout kills only the launcher stub and can leave its backend child running against the shared Studio home, contaminating subsequent repeats; return only after a successful taskkill and otherwise execute the fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, check=False makes a nonzero taskkill a silent success path, so the unconditional return skipped proc.terminate() and even the stub survived until the wait(timeout=30). Fixed in 1d436af: it returns only on returncode == 0 and otherwise falls through. The fallback is safe for the already-gone case (taskkill 128) too, because Windows Popen.terminate() returns early once returncode is set and swallows ERROR_ACCESS_DENIED unless GetExitCodeProcess still reports STILL_ACTIVE (CPython subprocess.py), so the fix does not depend on which nonzero code taskkill picked. Covered by test_terminate_tree_falls_back_when_taskkill_fails, which asserts the /T /F argv and that terminate() is reached.

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Invoke the resolved Python on Windows

The Windows hosted runner exposes the toolcache interpreter as python.exe and this job does not run actions/setup-python to provide a python3 command, so the hard-coded invocation can fail before the profiler starts even though the preceding fallback successfully resolved PY via command -v python. Use a resolved driver (python3 || python, or the installed PY) here and in the Summary step so the Windows matrix actually emits a profile.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seventh report of this line, after 3668528736, 3668689399, 3668919485, 3670011161, 3670135405 and 3670247939. Nothing below the paths: block has changed since, so the same evidence applies: run 30372438698's startup windows-latest job concluded success running this exact python3 scripts/profile_startup.py and reported import main: 17.507s, and the Summary step's python3 heredoc ran and uploaded startup-windows-latest.json in that job. The step is shell: bash, which on windows-latest is Git Bash, and both it and the hostedtoolcache Python put a python3 on PATH. Line 106 is a last resort that never fires on Windows because 105 already resolves Scripts/python.exe, and $PY is handed to the profiler via --python to profile the venv interpreter, not to run the controller.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8726de0fd4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +35 to +37
- 'install.sh'
- 'install.ps1'
- 'pyproject.toml'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Trigger profiling for Studio setup changes

PRs that modify studio/setup.sh, studio/setup.ps1, or studio/install_python_stack.py will not run this workflow, even though the local installers execute those checkout files (install.sh selects studio/setup.sh at lines 4177-4184, and both setup scripts invoke install_python_stack.py) to construct the exact venv being profiled. Changes to dependency selection or setup behavior can therefore alter startup time without producing any measurements; include these Studio setup paths, or the relevant top-level studio/ installer files, in the trigger.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and I verified the chain rather than taking it on trust. install.sh line 4182 picks $_REPO_ROOT/studio/setup.sh under --local; install.ps1 skips its overlay under --local because the editable install makes _PACKAGE_ROOT resolve to the repo, so unsloth studio setup runs the checkout's setup.ps1; setup.sh line 972 and setup.ps1 line 3400 both run install_python_stack.py, which is where the pip installs happen. So the venv being profiled is built from those three files and none of them scheduled a run.

Added them to paths: in f315562, plus a test that fails on the old trigger list: test_workflow_triggers_on_studio_installer_inputs parses the workflow and matches each file against the non-negated globs, and test_studio_installer_inputs_are_on_the_local_install_path anchors why the list has those three entries. Against the pre-fix workflow: 3 failed, 9 passed. After: 12 passed.

Left setup.bat out: nothing in install.sh or install.ps1 invokes it.

install.sh --local runs the checkout's studio/setup.sh, install.ps1 reaches
studio/setup.ps1 through the editable install, and both call
install_python_stack.py, which decides the dependency set that gets imported.
Editing any of them could change startup time with no measurement taken.
Comments and docstrings only.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f315562075

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/bin/python"
[ -x "$PY" ] || PY="$UNSLOTH_STUDIO_HOME/unsloth_studio/Scripts/python.exe"
[ -x "$PY" ] || PY="$(command -v python3 || command -v python)"
python3 scripts/profile_startup.py \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run the profiler with the interpreter you resolved

On a runner where python exists but python3 does not, the fallback immediately above correctly assigns that executable to PY, but this command still invokes python3 unconditionally. This is especially relevant to the Windows matrix cell and can leave it with no profile while the job remains green because continue-on-error is enabled; the Summary step repeats the same unconditional invocation. Launch both the profiler and summary with the resolved interpreter, or explicitly provision a guaranteed system Python command.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the seventh time this line has been flagged and it stays disproved by the job itself. Run 30395166099, job startup windows-latest, conclusion success: the log shows python3 scripts/profile_startup.py \ executing and producing import main: 17.426s, three launches, median time to healthy port: 8.28s, and the Summary step's python3 - "$f" running too. shell: bash on windows-latest is Git Bash, where python3 resolves. The || command -v python tail is a last-resort guard for the import interpreter, not evidence that python3 is absent. Nothing under paths: or in either step has changed since that green run.

Comment on lines +327 to +331
report["launch"] = {
"runs": runs,
"failed_runs": sum(1 for r in runs if not r["reached_healthz"]),
"healthz_median_seconds": round(statistics.median(got), 3) if got else None,
"healthz_max_seconds": round(max(got), 3) if got else None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report aggregates for the spawn and lifespan phases

With the workflow's default three repeats, this report aggregates only healthz_seconds; spawn_seconds and lifespan_ms remain buried in individual runs and are also omitted from the workflow summary. Consequently the CI output does not provide the advertised median/max breakdown for those phases, so consumers cannot directly compare where startup time shifted across platforms or commits. Compute and expose aggregates for every measured phase.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing advertises per-phase aggregates: --repeats documents "the median is reported" for the single gated metric, and the budget is healthz-only. spawn_seconds and lifespan_ms are already emitted per run to stdout and stored per run under launch.runs[] in the JSON artifact, so a consumer comparing platforms or commits has the raw values. Adding two more medians to the summary is a presentation preference, not a correctness bug, so I am leaving it out.

# taskkill missing or timed out; fall through so the stub still dies.
pass
# check=False: a nonzero taskkill does not raise, so fall through as well.
proc.terminate()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the Windows backend handle when taskkill fails

When taskkill is unavailable, times out, or returns nonzero, this fallback calls terminate() on the distlib launcher even though _terminate_tree explicitly documents that terminating that stub does not terminate its backend child. In that failure scenario the real server retains the stdout pipe, the reader can survive its join timeout, and repeated profiles can strand running backends. Spawn the Windows process under a mechanism that can always terminate the tree, or retain and terminate the actual Python child rather than treating launcher termination as a sufficient fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The premise is right but the path is not reachable: taskkill.exe ships in %SystemRoot%\System32 on every supported Windows including the windows-latest image, and the taskkill /PID /T /F call is what actually reaps the tree. The terminate() after it is a last resort for an environment where taskkill is gone or hung, and there reaping the stub is strictly better than reaping nothing. The alternatives suggested need a job object, i.e. pywin32, which this script cannot import: it runs under the runner's system Python, not the Studio venv. The leak is bounded anyway (wait(timeout=30) then kill(), daemon reader thread), and the ports are fresh per repeat.

Comment on lines +86 to +88
pwsh -NoProfile -File ./install.ps1 --local 2>&1 | tee logs/install.log
else
bash install.sh --local 2>&1 | tee logs/install.log

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pin the dependency used for startup comparisons

Both --local installer paths reinstall unsloth-zoo from an unpinned Git main revision, and the profiler itself identifies that package as a substantial import-time contributor. Thus two runs of the same Unsloth commit can report different startup numbers solely because the external repository advanced, while the JSON does not record its commit, undermining longitudinal comparisons and any later budget derived from these artifacts. Pin the revision for this workflow or record the exact installed commit and use it when comparing results.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overlay is real (install.ps1 and install.sh both do unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo with no rev), but it is pre-existing installer behaviour and pinning it here would measure a configuration no user gets. The point of the job is to profile exactly what install.sh --local builds. Being straight about the limitation: the resolved zoo commit is not recorded, the installer's progress output swallows uv's resolution line, so I cannot claim the artifact carries it. It does not change the verdict, because the workflow is continue-on-error: true with no --max-healthz-seconds, so nothing is gated on these numbers, and hosted runner variance already dominates: the same commit measured 8.28s median on windows-latest against low single digits on ubuntu. A zoo pin would add false precision on top of that.

- '!studio/backend/tests/**'
# The launch phase spawns `unsloth studio --api-only`, so the CLI counts too.
- 'unsloth_cli/**'
- 'studio/src-tauri/src/preflight**'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Trigger profiling when the desktop launch command changes

The actual desktop backend command is constructed in studio/src-tauri/src/process.rs::backend_args, including the studio --api-only -H ... -p ... arguments that this profiler duplicates, but the path filter includes only the Tauri preflight files. A PR that changes the desktop command, binary resolution, or spawning behavior in process.rs therefore neither schedules this workflow nor prompts the hardcoded profiler command to be updated, allowing the measurement to silently diverge from the launch it claims to model. Include the process launcher in the trigger set.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 67ea75f. backend_args builds exactly studio --api-only -H 127.0.0.1 -p <port>, which is the argv profile_launch hardcodes, so studio/src-tauri/src/process.rs is now in paths:. Added a test that parses both lists (regex over the Rust fn body, AST over the Popen call) and asserts they are identical, so a divergence fails rather than just going unmeasured.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f8428194c9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +275 to +277
"--max-healthz-seconds",
type = float,
help = "fail if the median time to a healthy port exceeds this",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject NaN health budgets

When a caller supplies --max-healthz-seconds nan, argparse accepts it as a float, and after healthy launches the comparison med > a.max_healthz_seconds is always false, so the command exits successfully regardless of the measured startup time. Validate that the budget is finite during argument parsing so malformed input cannot silently disable the gate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, fixed in 67ea75f. --max-healthz-seconds=nan and =inf both parse as floats and med > budget is then always False, so the gate exited 0 on any measured median. main now rejects a non-finite budget alongside the existing --repeats/--import-only validation. Regression test covers nan, inf and -inf against a mocked healthy launch: red on the pre-fix file (returns 0 instead of exiting 2), green after.

…hanges

--max-healthz-seconds nan or inf parses as a float but compares False against
any median, so the gate reported success without bounding anything. Require a
finite value.

The profiler hardcodes the argv that process.rs::backend_args builds, but that
file was not in the trigger paths, so a change to the desktop launch command
scheduled no measurement. Add it, and anchor the two argv lists with a test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: b91f6ca12a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit bd39728 into main Jul 29, 2026
18 checks passed
@danielhanchen
danielhanchen deleted the perf/startup-profiling branch July 29, 2026 05:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants