# Comment evaluation corpus -- py-docstring, needs labels
#
# Real own-line comments with the code that follows. Mark every `verdict:` as:
#
#   slop  - should not exist: restates the code, narrates an edit, labels a
#           section, leaks process, records history, or is a long explanation
#           where a short one would do
#   keep  - deleting it would lose a fact not recoverable from the code
#   skip  - genuinely cannot tell without more context
#
# Leave `?` on anything you do not reach; partial labelling still scores.
#
# Nothing here reveals which rule (if any) fires on a case, or how the case
# was sampled.

### 1  agent-service/agent_service/routes.py:201
# Interrupt the in-flight turn for a conversation, if one is running.
#
# Stops the agent server-side (frees the turn slot, ends token spend); the
# partial output already streamed is kept. Idempotent — a no-op when nothing
# is running.
#
# Waits for the turn to actually unwind before answering, rather than
# reporting success the moment the stop is *requested*. The turn only stops
# at a checkpoint — and an in-flight ``run_python`` cell has to be killed and
# reaped first — so an immediate reply let the client re-enable the composer
# while ``running`` was still set, and the next prompt came back 409. The
# ``running`` field says whether it is genuinely finished, so a client can
# keep input disabled in the rare case it is not.
#
    await get_owned_session(conversation_id, user_id, bearer_token(request) or "")
    conversation = conversation_manager.get(conversation_id, user_id)
    if conversation is None:
    return {"stopped": False, "running": False}
verdict: ?

### 2  backend/src/jobs/processors/pipeline.py:1586
# Create one progress-view child row per multistart, without dispatch.
#
# Returns ``{start_id: child_job_id}`` keyed ``"0"``..``"N-1"`` so the
# ``SupabaseSink`` can map each ``StartStatusChanged.start_id`` to the row
# that mirrors it.
#
# These rows are **progress views, not units of work**. Each is created
# with the bare :meth:`JobController.create_job` (carrying
# ``parent_job_id``) and is deliberately **never submitted**: the
# coordinator drives every start in the driver process, so there is
# nothing to enqueue. Using ``create_and_submit_job`` here would be
# wrong — it would enqueue a unit of work that no processor would
# ever run. The rows are not zombies: the sink drives each to a terminal
# status, and if the driver dies the parent-timeout cascade
# (``fail_children``) finalizes them within the parent's lifetime.
#
# Parameters
# ----------
# supabase_service : Client
# Supabase service client used to create the rows.
# parent_job_id : str
# UUID of the parent datafit job; links each view row to its parent.
# organization_id : str
# Organization that owns the parent job.
# user_id : str
# User who initiated the parent job.
# job_type : str
# Job type recorded on each view row (matches the parent's type).
# num_jobs : int
# Number of multistarts the fit will run — one view row per start.
#
# Returns
# -------
# dict[str, str]
# Mapping of start id (``"0"``..``"N-1"``) to the created child job id.
#
    controller = JobController(supabase_client=supabase_service)
    resolved_job_type = JobType(job_type)
    child_ids: dict[str, str] = {}
    for start_id in range(num_jobs):
verdict: ?

### 3  backend/src/routes/channels.py:331
# List the channel's outage spans, most recently started first.
#
# An open incident (``resolved_at`` null) is the channel's current outage;
# at most one can exist. Rows with ``is_estimated`` true were reconstructed
# from the channel's last-modified time when outage history was introduced, so
# their ``started_at`` is an upper bound rather than a recorded event.
#
    result = await service.list_incidents(
    organization_id, channel_id, limit=limit, offset=offset
    )
    return JSONResponse(content=jsonable_encoder(result.to_response_dict()))
verdict: keep

### 4  backend/src/services/cell_events.py:240
# Notify subscribers that a cell measurement was created/updated/deleted.
#
# ``cell_measurement.created`` fires when the measurement row exists, which
# for an uploaded measurement is before its steps have been processed — the
# snapshot therefore describes the record, not a finished dataset. Subscribers
# that need processed steps should read ``processing_status`` from the API.
#
# Parameters
# ----------
# event : WebhookEvent
# One of the ``cell_measurement.*`` members.
# measurement_id : str
# Measurement the event is about.
# cell_instance_id : str or None
# Parent instance, included in ``data``.
# project_id : str or None
# Project owning the measurement. A missing value drops the event.
# organization_id : str or None
# Organization owning the measurement. A missing value drops the event.
# name : str or None, optional
# Measurement name at the time of the event.
# measurement_type : str or None, optional
# ``properties``, ``time_series``, or ``file``.
# client : AsyncClient, optional
# Service-role client to enqueue with.
#
    await _emit_cell_event(
    event=event,
    resource_type=RESOURCE_CELL_MEASUREMENT,
    resource_id=measurement_id,
verdict: keep

### 5  backend/src/simulation/services/parameterized_model_service.py:83
# Load a PyBaMM model from a model dict.
#
# This is the core method for loading models from the dict format used
# in ParameterizedModel.model. Works for both custom models (with
# compressed data) and standard models (built from config).
#
# Parameters
# ----------
# model_dict : dict[str, Any]
# Model dict with keys: id, name, config, custom_model_data
#
# Returns
# -------
# pybamm.lithium_ion.BaseModel
# The PyBaMM model instance
#
#
    custom_model_data = model_dict.get("custom_model_data")
    chemistry = model_dict.get("chemistry") or "lithium_ion"
    if custom_model_data:
    pybamm_model = ModelService.load_custom_model_from_data(
verdict: keep

### 6  backend/tests/integration_db/repositories/test_cycler_service_overlapping_window.py:164
# A booked visit with no end is treated as open-ended, so it collides.
#
# An unknown end cannot be ruled out, and for a collision check the
# conservative direction is to report the clash and let a human resolve it —
# the opposite choice would quietly schedule work onto an instrument nobody
# can promise is back.
#
    started_before = await _book(
    svc_client,
    org_id,
    project_id,
verdict: ?

### 7  backend/tests/test_architecture/test_event_registry.py:51
# Parse the ``WebhookEvent`` TypeScript union members.
    source = FRONTEND_API.read_text()
    block = re.search(r"export type WebhookEvent\s*=(.*?);", source, re.DOTALL)
    assert block is not None, "could not locate the WebhookEvent union"
    return set(re.findall(r"""['"]([^'"]+)['"]""", block.group(1)))
verdict: ?

### 8  backend/tests/test_jobs/test_simple_pipeline_processor.py:77
# Patch the sync chokepoint the processor writes status through.
    service = MagicMock()
    service.set_status = MagicMock(**set_status_kwargs)
    return service, patch(
    "src.jobs.processors.simple_pipeline.SyncPipelineStatusTransitionService",
verdict: ?

### 9  backend/tests/test_repositories/test_cell_measurements_channel_overlap.py:118
# The span searched must be the one the write *tried* to set.
#
# The rejected write rolled back, so the stored row still holds the old values.
# Searching with those looks for a conflict that was never proposed — the
# payload has to win over storage.
#
    @pytest.mark.asyncio
    async def test_payload_overrides_stored_values(self):
    repo = _make_repo()
    repo.get_by_id = AsyncMock(
verdict: ?

### 10  backend/tests/test_routes/test_optimization_template_copy.py:199
# A newly created project template records who created it.
#
# The route previously discarded the user id from the auth tuple
# (``_, organization_id, _``), so the column would have stayed NULL.
#
    response = client.post(
    "/optimization_templates",
    json={
    "name": "New Template",
verdict: ?

### 11  backend/tests/test_services/test_analysis_service.py:603
# update() writes the source FK into the update payload.
    analysis_repo.get_analysis.return_value = _record()
    analysis_repo.update.return_value = _record(source_pipeline_id=PIPE_UUID)
    await svc.update(
    ANALYSIS_ID,
verdict: ?

### 12  backend/tests/test_services/test_anyscale_service.py:1699
# Console-filterable tags attached to every batch job submission.
    def _full_job(self):
    return SimpleNamespace(
    job_id="job-1",
    job_type=JobType.DATA_FIT,
verdict: ?

### 13  packages/ionworks-api/ionworks/models.py:656
# Flat response from creating a measurement bundle.
#
# Measurement fields (id, name, measurement_type, etc.) are at the top level
# alongside upload metadata.
#
    steps_created: int
    class UploadInfo(BaseModel):
verdict: ?

### 14  packages/ionworks-api/ionworks/models.py:1017
# Result of parsing a vendor protocol file into UCP.
#
# Returned by :meth:`~ionworks.protocol.ProtocolClient.parse_file`. A parsed
# protocol is not saved — pass ``ucp`` to
# :meth:`~ionworks.protocol.ProtocolClient.create` to store it.
#
# Drive cycles and subroutines referenced by the file may not be embedded in
# it. Those the parser recovered are listed in ``available_drive_cycles`` /
# ``available_subroutines``; those still needed are in the ``required_``
# lists and must be supplied before the protocol will simulate.
#
    model_config = ConfigDict(extra="allow", populate_by_name=True)
    ucp: str = Field(alias="parsed_protocol_ucp")
verdict: slop

### 15  packages/ionworks-api/ionworks/protocol.py:1
# Protocol client for authoring, saving, and converting UCP protocols.
#
# Provides :class:`ProtocolClient` for the whole protocol lifecycle: writing a
# protocol (by hand or by parsing a vendor file), validating it, saving it to a
# project so simulations and planned measurements can reference it by id, and
# converting it back out to a vendor-native protocol file (Maccor, Arbin,
# Neware, BioLogic BT-Test, Novonix).
#
# Saved protocols are stored as ``experiment_template`` rows server-side; the
# SDK calls them protocols throughout.
#
    from __future__ import annotations
    import base64
    from dataclasses import dataclass, field
    from pathlib import Path
verdict: ?

### 16  packages/ionworks-api/tests/test_simulation_result.py:1
# Tests for SimulationResult typed return and _dict_of_lists_to_df helper.
    from __future__ import annotations
    from unittest.mock import MagicMock
    from ionworks import SimulationResult, set_dataframe_backend
verdict: ?

### 17  packages/ionworks-schema/src/ionworks_schema/validation.py:17
# Check a fitted model against held-out experimental data.
#
# A ``Validation`` step takes the parameters produced earlier in the
# pipeline, simulates the experiments listed in ``objectives``, and
# compares those simulations to the measured data. The result tells
# you how well the model generalises beyond the data you fit on.
#
# Each ``objective`` describes one comparison (e.g. "current vs.
# time for this discharge"). The ``summary_stats`` list controls
# which scalar error metrics — RMSE, MAE, max error, … — get
# reported alongside the full time-series comparison.
#
# Parameters
# ----------
# objectives : dict of name to objective or dict
# One entry per experiment you want to compare against. The key
# is a human-readable label (used in the report); the value is
# the objective describing what to simulate and what to compare.
# summary_stats : list[Cost | dict], optional
# Which scalar error metrics to report (e.g. ``RMSE()``,
# ``MAE()``, ``Max()``). If you leave this unset, sensible
# defaults are filled in for fitting-style objectives so the
# report carries the same physical units as the measurements.
#
# Examples
# --------
# >>> obj1 = iws.objectives.CurrentDriven(
# ...     data_input="path/to/cycle_1C.csv", options={"model": "SPM"}
# ... )
# >>> obj2 = iws.objectives.CurrentDriven(
# ...     data_input="path/to/cycle_C2.csv", options={"model": "SPM"}
# ... )
# >>> val = iws.Validation(
# ...     objectives={"1C": obj1, "C/2": obj2},
# ...     summary_stats=[iws.costs.RMSE(), iws.costs.MAE()],
# ... )
# >>> config = iws.Pipeline({"validate": val}).to_config()
# >>> # then submit `config` via ionworks-api
#
    objectives: dict[str, ObjectiveUnion] = Field(
    ...,
    description=(
    "One entry per experiment you want to validate against. "
verdict: slop - overly verbose

### 18  packages/ionworks-ucp/ionworks_ucp/parsers/biologic_mps_parser.py:1314
# Append a ``set_variable`` to the first runnable op inside the step.
#
# The simulator's ``_update_variables`` fires per StandardStep (and
# also at end-of-block), so we attach the declaration to the inner
# ``Charge`` / ``Discharge`` / ``Rest`` op — keeping the variable
# co-located with the step whose final voltage it captures.
#
# Handles both shapes produced by :meth:`_convert_step_to_ucp`:
# the simple list-body ``{name: [{Charge: {...}}]}`` and the
# block-shape ``{name: {"steps": [...], ...}}`` (CC-CV). Loop
# placeholders are skipped silently.
#
    if flat_entry.get("__type__") == "Loop":
    return
    for step_body in flat_entry.values():
    if isinstance(step_body, dict):
verdict: keep

### 19  packages/ionworks-ucp/ionworks_ucp/parsers/ucp_to_arbin.py:31
# Convert a Universal Cycler Protocol (UCP) to an Arbin INI-style
# schedule.
#
# Supported features (aligned with our Arbin parser):
# - Rest, Charge/Discharge (Current, C-rate, Power), Voltage steps
# - Duration and custom end conditions (Voltage, Current, C-rate)
# - Per-step data recording resolution (time/voltage/current)
# - Goto by named step labels
# - Initialize Variables → ``m_fMV_UD*`` header entries
# - TC_Counter operations → Set Variable(s) bitmasks
# - Multiple MV_UD SetValue(s) entries
#
# Returns bytes containing the INI text suitable for .sdu
# consumption by our parser (round-trip friendly).
#
#
    _RESET_MASK_VARS = [
    "PV_CHAN_Charge_Capacity",
    "PV_CHAN_Discharge_Capacity",
    "PV_CHAN_Charge_Energy",
verdict: keep

### 20  packages/ionworks-ucp/ionworks_ucp/replay.py:982
# The recorded value a threshold condition would have fired on.
#
# ``None`` for anything a step summary does not carry: temperature and
# electrode potentials are absent entirely, a C-rate would need the cell's
# capacity to become amps, and a derivative condition needs the trace rather
# than the summary.
#
# Voltage is exact -- the summary records the step's last value. Current is
# not: only min/max/mean are kept, so the extreme in the direction the
# condition tests stands in for the final value. That is the same number for a
# constant-current step, and for a taper it is the value the decay reached,
# which is what the condition was watching.
#
# Capacity is exact too: the summary's capacity columns are already the step's
# own throughput (``last - first``), and the net figure is assembled the way
# the executor's ``Step capacity [A.h]`` is -- see :func:`_step_capacity`.
#
    if end.derivative:
    return None
    if end.type == EndType.VOLTAGE:
    return _as_float(row.get("End voltage [V]"))
verdict: slop

### 21  packages/ionworks-ucp/ionworks_ucp/simulate_protocol.py:3033
# Run a protocol simulation using a pre-built simulation environment.
#
# Executes a simulation built by build_protocol_simulation(). Inputs may be
# passed at solve time to override the step values defined in the protocol;
# only inputs explicitly marked as input["..."] in the protocol can be passed.
#
# The returned UCPSolution contains the raw state vectors from the simulation,
# allowing any model variable to be evaluated later using the `evaluate()` method.
# To get the traditional DataFrame output, call `solution.to_dataframe()`.
#
# Parameters
# ----------
# sim : SimulationEnvironment
# A simulation environment returned by build_protocol_simulation().
# inputs : dict, optional
# Dictionary of input parameters to override step values at solve time.
# Only inputs explicitly marked as input["..."] in the protocol are
# allowed. For example, if the protocol contains input["C-rate"], then
# you can pass {"C-rate": 1.0} to override it.
# checkpoint_func: Optional[Callable[[int, float], bool]]
# Optional function to call for progress reporting. Takes (step_count,
# current_time) and returns True to continue or False to stop.
# progress_state: Optional[Any]
# Optional state object for progress reporting. Each step sets
# ``.detailed_message`` and ``.use_detailed_message`` — a
# ``__slots__``-based object must declare both.
# starting_solution: Optional[pybamm.Solution]
# Optional starting solution to continue from a previous simulation.
# writer : StepSolutionWriter, optional
# Pre-configured writer that handles memory tracking, spill-to-disk,
# and optional streaming chunk uploads.  When ``None`` (the default),
# a writer with default settings (1 GB memory cap, no filepath, no
# chunk callback) is created automatically.
# variable_callback: Optional[VariableCallback]
# Optional callback function for simulating external equipment responses.
# Called after each control step with (variables). Can return a dict of
# variable updates to apply. This enables simulation of external equipment
# like EIS analyzers that respond to protocol commands.
#
# Example for EIS equipment::
#
# def mock_eis(variables: dict) -> dict | None:
# # When MV_UD2 is set to 1 (protocol waiting for response),
# # respond with ready signal (MV_UD2=3)
# if variables.get("MV_UD2") == 1:
# return {"MV_UD2": 3}
# return None
#
# termination_condition: Optional[TerminationCondition]
# Optional callback evaluated after every step.  Receives the current
# protocol variables dict and returns ``True`` to stop the simulation
# early.  Useful for ending a long protocol once a target cycle count
# or variable threshold is reached.
#
# Example::
#
# # Stop after 3 cycles
# def stop_after_3(variables: dict) -> bool:
# return variables.get("PV_CHAN_Cycle_Index", 0) >= 4
#
# treat_pause_as_rest : bool, optional
# When True, ``pause`` auxiliary steps are skipped (treated as a
# zero-duration rest) so the simulation continues through them. When
# False (the default), pause steps end the simulation in the same way
# as ``end`` steps. Useful for cycler protocols where pauses mark
# operator-attended breakpoints that should be ignored when running
# the protocol unattended in simulation.
# run_start : RunStart, optional
# Where the run loop begins. Defaults to a from-scratch run (first step,
# reset experiment, clock at zero). To resume, pass ``resume_step`` set
# to the step to start at (the experiment must already be positioned
# there, e.g. by :class:`ResumeFromState`), ``skip_reset=True`` (a reset
# would wipe that position), and ``start_time_s`` as the absolute time
# offset for the returned solution's timestamps.
#
# Returns
# -------
# UCPSolution
# A solution object containing the raw state vectors. Use `to_dataframe()`
# to convert to the traditional (time_series, steps) DataFrame tuple, or
# use `evaluate()` to compute any model variable from the saved state.
#
# Raises
# ------
# ValueError
# If inputs are provided that are not explicitly marked in the protocol.
#
# Examples
# --------
# >>> sim = build_protocol_simulation(protocol, model, params)
# >>> solution = run_protocol_simulation(sim, inputs={"C-rate": 0.5})
# >>> # Get traditional DataFrame output
# >>> df, steps = solution.to_dataframe(model, params)
# >>> # Or evaluate specific variables
# >>> voltage = solution.evaluate("Voltage [V]", model, params)
# >>> # Save for later
# >>> solution.save("solution.parquet")
# >>> # For long-running simulations, write directly to a file:
# >>> from ionworks_ucp.step_writer import StepSolutionWriter
# >>> writer = StepSolutionWriter(
# ...     filepath=f"{storage_folder}/solution.parquet",
# ...     max_memory_bytes=500_000_000,  # 500 MB
# ... )
# >>> solution = run_protocol_simulation(sim, writer=writer)
#
#
    if inputs is None:
    inputs = {}
    if inputs:
    sim.input_manager.validate_inputs(inputs, context="runtime")
verdict: slop

### 22  packages/ionworks-ucp/tests/test_drive_cycles.py:231
# After loading the file, the protocol can be simulated
# end-to-end.
    parsed = parse_protocol(arbin_sdx, require_additional_content=False)
    wltp_data = load_arbin_drive_cycle(wltp_path)
    drive_cycles = {"WLTP_5Ah_10%_1800s.txt": wltp_data}
verdict: ?

### 23  packages/ionworks-ucp/tests/test_replay_cycler_reality.py:205
# The trap that makes coalescing dangerous, held down by a test.
#
# A repeat block with one runnable child runs that child three times, and a
# cycler numbers all three with the step's own number -- indistinguishable from
# one step logged in three pieces, by the data alone. Joining them would report
# one iteration where three happened and lose the loop count.
#
# Replay declines to join them because the graph says the node can be reached
# again immediately. Deleting that check makes this test fail rather than
# silently under-counting a loop.
#
    rows = [
    {
    "Step type": "Constant current discharge",
    "Duration [s]": 120.0,
verdict: ?

### 24  packages/ionworksdata/ionworksdata/read/maccor.py:551
# Map the correct Maccor cycle column to ``Cycle from cycler``.
#
# Maccor exports up to two cycle columns: ``Cycle C`` (the cumulative
# cycle counter, always the true cycle number) and ``Cycle P`` (a
# procedure-level loop counter whose meaning depends on how the Maccor
# procedure was written — often 0, sometimes equal to ``Cycle C``).
# ``Cycle C`` is therefore preferred whenever present. ``Cycle P`` is
# used only as a fallback when ``Cycle C`` is absent, so files that
# expose only ``Cycle P`` still get a ``Cycle from cycler`` column (see
# issue #2).
#
# Parameters
# ----------
# data : pl.DataFrame
# Raw data whose columns determine which cycle column to map.
# column_renamings : dict[str, str]
# Column renaming dictionary to update in place.
#
# Returns
# -------
# dict[str, str]
# The updated ``column_renamings`` dictionary.
#
    if "Cycle C" in data.columns:
    column_renamings["Cycle C"] = "Cycle from cycler"
    elif "Cycle P" in data.columns:
    column_renamings["Cycle P"] = "Cycle from cycler"
verdict: slop

### 25  packages/ionworkspipeline/src/ionworkspipeline/data_fits/objectives/pulse.py:320
# Simply return the voltage from the data
#
#
    return {"Voltage [V]": df["Voltage [V]"].to_numpy()}
    def _get_previous_voltage(df, step_num):
    if step_num == 0:
verdict: ?

### 26  packages/ionworkspipeline/src/ionworkspipeline/data_fits/parameter_estimators/optimizers/algorithms/bayesian_optimization.py:179
# Build the unconstrained log-EI acquisition.
    if self._batch_size == 1:
    return LogExpectedImprovement(self._gp_model, best_f=best_f)
    return qLogExpectedImprovement(self._gp_model, best_f=best_f)
    def _build_constrained_acquisition(self, best_f):
verdict: ?

### 27  packages/ionworkspipeline/src/ionworkspipeline/data_fits/stats/stats.py:1244
# Whether the distribution has zero variance.
#
# Returns
# -------
# has_zero_variance : bool
# Always True for point mass.
#
#
    return True
    def ppf(self, U: np.ndarray) -> np.ndarray:
    Percent point function (inverse of CDF) - transform samples from the standard uniform
    distribution to the point mass distribution.
verdict: ?

### 28  packages/ionworkspipeline/src/ionworkspipeline/exceptions.py:32
# Raised when a model fails to set up, discretise, initialise, or evaluate.
#
# Wraps an underlying failure that occurred while building or running a model
# for an objective — e.g. an incomplete parameter set, a model that cannot be
# discretised, or a failed state-of-charge initialisation. These are almost
# always user-correctable configuration problems rather than internal bugs, so
# this subclasses ``UserConfigurationError`` (preserving the optimizer's
# ``except ValueError`` NaN-fallback). The backend job layer routes it to a
# dedicated ``MODEL_ERROR`` code — distinct from the generic
# ``CONFIGURATION_ERROR`` so model-specific failures can be surfaced
# separately — and shows the message to the user instead of an opaque
# "unexpected error" (no Sentry). Being a ``UserConfigurationError`` subclass,
# it must be checked before that branch in any exception classifier.
#
# Parameters
# ----------
# message : str
# Human-readable description naming the objective and the underlying
# failure, written for the end user.
#
    class ParameterNotFoundError(KeyError):
    Subclasses ``KeyError`` so existing ``except KeyError`` handlers remain
verdict: slop

### 29  packages/ionworkspipeline/tests/unit/test_datafits/test_models/test_actions.py:197
# Test that GreaterThan returns inf for NaN input.
    metric = Minimum("Voltage [V]")
    constraint = GreaterThan(metric, value=3.0, penalty=1e6)
    assert constraint.apply(np.nan) == np.inf
    assert constraint.apply(np.array([np.nan, np.nan])) == np.inf
verdict: ?

### 30  packages/ionworkspipeline/tests/unit/test_datafits/test_models/test_custom_set_initial_state.py:239
# Case 9: '3.8 V'.
    func, pv, _ = model_and_pv
    result = func("3.8 V", pv)
    assert 0 < result["Initial SOC"] < 1
    def test_voltage_string_no_space(self, model_and_pv):
verdict: slop

### 31  packages/ionworkspipeline/tests/unit/test_datafits/test_models/test_custom_set_initial_state.py:554
# Case 27 (ECM): voltage within range.
    pv = _ecm_parameter_values()
    soc = iwp.models.ECM.get_initial_soc_from_voltage(3.35, pv)
    expected = (3.35 - 2.5) / 1.7
    assert 0 < soc < 1
verdict: slop

### 32  packages/ionworkspipeline/tests/unit/test_datafits/test_nested_datafit.py:1
# End-to-end tests for the Nested optimizer against a real ``iwp.DataFit``.
#
# These exercise the full path: objective build, mode selection from
# ``Nested.scalar_output``, the shared logged objective, and final-parameter
# extraction via ``cost_logger.x_best()``. Deep-recursion numerics are covered by
# the fast fake-harness tests in
# ``test_parameter_estimators/test_nested.py``; here we keep the parameter subset
# small and the outer optimizer derivative-free (the concentrated objective is
# mildly noisy through the inner solve) so the suite stays fast and robust.
#
    import ionworkspipeline as iwp
    import pytest
    from .conftest import lotka_volterra_objective
verdict: keep

### 33  packages/ionworkspipeline/tests/unit/test_datafits/test_parameter_estimators/test_optimizers/test_de_algorithm.py:523
# Classic strategies should not use archive.
    np.random.seed(42)
    x0 = np.array([5.0, 5.0])
    bounds = RectangularBoundaries([-10.0, -10.0], [10.0, 10.0])
    de = DifferentialEvolution(
verdict: ?

### 34  packages/ionworkspipeline/tests/unit/test_datafits/test_parameter_estimators/test_optimizers/test_de_algorithm.py:863
# rand_2 with pop_size < 6 should raise at initialization.
    x0 = np.array([1.0, 1.0])
    de = DifferentialEvolution(
    n_parameters=2, options={"mutation_strategy": "rand_2"}, population_size=5
    )
verdict: ?

### 35  packages/ionworkspipeline/tests/unit/test_direct_entries/test_piecewise_interpolation.py:809
# Test the module-level compute_knot_values_2d function directly.
    from ionworkspipeline.direct_entries.piecewise_interpolation import (
    compute_knot_values_2d,
    )
    param_names_grid = [
verdict: ?

### 36  packages/ionworkspipeline/tests/unit/test_parser_schemas/test_design_optimization_schema.py:701
# Confirm the retired resource fields are absent from the schema.
    fields = DesignOptimizationDataFitConfigSchema.model_fields
    assert "num_workers" not in fields
    assert "parallel" not in fields
    assert "max_batch_size" not in fields
verdict: ?

### 37  packages/ionworkspipeline/tests/unit/test_simulation.py:12
# iwp.Simulation.solve raises NumericalError when pybamm returns EmptySolution.
    def test_empty_solution_raises_numerical_error(self):
    raises NumericalError so the datafit can treat it as a failed iteration."""
    model = pybamm.lithium_ion.SPM()
    sim = iwp.Simulation(model)
verdict: ?

### 38  packages/private-skills/skills/make-deck/scripts/deck.py:411
# Brand title slide, template-agnostic.
#
# If the template has a brand title layout (a layout with a text shape
# whose text exposes any of the cues in TITLE_FIELD_CUES), classify each
# paragraph and replace it with the matching customer/date content. Where
# that text must be written depends on the template, because the two shape
# kinds clone differently into a new slide:
# - a *placeholder* title shape is cloned EMPTY onto the slide (its layout
# text does not transfer), so write into the slide's own placeholder;
# - a plain *text box* is not cloned at all and renders via layout
# inheritance, so mutate the layout shape in place.
# Both reference deck formats are covered this way.
#
# If no brand title layout is detected, fall back to SECTION_HEADER with
# everything in the title placeholder.
    lines = [
    "Ionworks update",
    f"Prepared for: {customer}",
    f"Date: {date}",
verdict: keep

### 39  packages/skills/skills/parameterize/assets/half_cell_msmr_template.py:295
# Single-phase MSMR parameter space. Joint hysteresis (DIRECTIONS has both
# directions) duplicates the species and lower-excess parameters per direction
# with a ``(direction)`` suffix, but keeps a SINGLE shared electrode
# capacity — one electrode has one capacity that both OCP branches must be
# consistent with.
#
# Capacities are seeded from the observed stoichiometry window (see
# ``_seed_capacities``): each direction gets its own lower-excess seed from its
# own data, and the shared total capacity is the LARGEST per-direction Q so
# theta stays <= 1 for every branch.
#
    E = ELECTRODE.capitalize()
    seed = _seed_single(SEED_MATERIAL)
verdict: keep

### 40  packages/skills/skills/parameterize/tests/test_full_cell_eis_current_driven_template.py:1
# Tests for the full-cell time-domain fit template (two-stage STAGE 2).
#
# Guards the contracts stage 2 is responsible for across its KINETICS_MODE levers:
#
# 1. **Model convention** — differential surface form + contact resistance; DFN switch.
# 2. **"pin" baseline** — the stage-1 kinetics are FIXED (in the known/static params,
# not in the fit), no EIS objectives, and transport/loading (f_solid) is fit.
# The Butler-Volmer wiring is present so the pinned j0ref reaches the model.
# 3. **"prior" soft pin** — the kinetics ARE fit, centred on the stage-1 values with
# tight Normal priors.
# 4. **"joint" escalation** — kinetics fit free, EIS objectives added back with the
# contact-R strict upper bound at R0, and a cross-objective cost.
# 5. **Guards** — composite + FIT_EPS_S raises; pin/prior without KINETICS_JSON raises.
#
    from __future__ import annotations
    import importlib.util
    import json
    from pathlib import Path
verdict: slop
