# Comment evaluation corpus -- needs labels
#
# Real own-line comments from this repo, each with the code that follows. Mark
# every `verdict:` as one of:
#
#   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.
#
# Wrapped comments are shown on their original lines. Sampling deliberately
# over-represents long and multi-line blocks: they are ~11% of real comments but
# they are what the `verbose` tier targets, and an earlier corpus that filtered
# them out could not test it at all.
#
# Nothing here reveals which rule (if any) fires on a case.

### 1  frontend/src/components/cycler-protocol/drive-cycle-override-uploader.tsx:41
# The override is keyed by the drive-cycle name, so accept any file the
# user picks rather than enforcing a name match.
    const handleFileChange = (driveCycleName: string) => (event: ChangeEvent<HTMLInputElement>) => {
    const newFile = event.target.files?.[0];
    if (!newFile) return;
    setDriveCycleFile(driveCycleName, newFile);
verdict: ?

### 2  frontend/src/components/cell/measurement-details-dvdq-tab.tsx:219
# Only auto-apply cycle filter after initial load completes (when !isDvdqLoading), so we don't
# stack a second fetch and risk races or stuck loading.
    useEffect(() => {
    if (!isDvdqLoading && dvdqNumCycles > DVDQ_MAX_CYCLES && !dvdqAutoFilteredRef.current) {
    dvdqAutoFilteredRef.current = true;
    dvdqAutoFilterFetchingRef.current = true;
verdict: ?

### 3  frontend/src/routes/sections/dashboard.tsx:258
# Single route with an OPTIONAL param, so navigating from /agent
# to /agent/:sessionId (on first message) stays on the same route
# and only updates the param — it does NOT remount AgentPage.
# Two separate entries (index + :sessionId) remounted it, which
# aborted the in-flight stream mid-turn and skipped its
# end-of-turn cleanup, leaving the turn stuck "running" (composer
# disabled, reply never persisted). ChatView still reads
# sessionId via useParams (undefined on the bare /agent path).
    path: 'agent/:sessionId?',
    element: <AgentPage />,
    },
    {
verdict: slop

### 4  packages/ionworkspipeline/src/ionworkspipeline/calculations/piecewise_conversion.py:471
# bp1-slope parameters for first row
    for i in range(len(self.breakpoint1_values) - 1):
    bp1_from = self.breakpoint1_values[i]
    bp1_to = self.breakpoint1_values[i + 1]
    slope_param_name = self._make_slope1_parameter_name(
verdict: keep

### 5  backend/tests/test_repositories/test_analysis_repository.py:324
# ---------------------------------------------------------------------------
    @pytest.mark.asyncio
    async def test_create_signed_download_url_returns_url(monkeypatch):
verdict: slop

### 6  packages/ionworkspipeline/src/ionworkspipeline/data_fits/parameter_estimators/optimizers/algorithms/sober/_prior_factory.py:159
# log_b(x) is Normal(mean/log_base, std/log_base).
    return TruncatedNormalPrior(
    loc=(dist.mean / log_base) / scale,
    scale=(dist.std / log_base) / scale,
    lower=lower,
verdict: keep

### 7  backend/src/parameter_library/graphite_half_cell.py:57
# Voltage cut-offs
    "Lower voltage cut-off [V]": 0.001,
    "Upper voltage cut-off [V]": 1.5,
    "Open-circuit voltage at 0% SOC [V]": 0.001,
    "Open-circuit voltage at 100% SOC [V]": 1.5,
verdict: keep

### 8  frontend/src/sections/agent/chat-view.tsx:948
# streamingRef is set only on the mount that started the turn; after the
# first-message navigation remount it's null, so fall back to sessionId.
    const sid = streamingRef.current ?? sessionId;
    if (sid) void stopAgent(sid);
    abortRef.current?.abort();
    }, [sessionId]);
verdict: ?

### 9  backend/tests/test_services/test_classify_exception.py:186
# A failure translating a UCP protocol into a PyBaMM experiment is a
# user-correctable configuration problem (it shares the
# CONFIGURATION_ERROR branch with ProtocolConfigurationError).
    from ionworks_ucp.parsers.ucp_to_pybamm import UCPToPyBaMMError
    msg = "Drive cycle steps are not supported when converting to PyBaMM."
    failure = classify_exception(UCPToPyBaMMError(msg))
    assert failure.error_code == JobErrorCode.CONFIGURATION_ERROR
verdict: slop

### 10  backend/src/simulation/services/simulation_service.py:201
# If protocol expansion already replaced DriveCycle references with
# Drive steps (e.g. via process_waveform_to_ucp), dc_names will be
# empty. Fall back to the additional_content keys (minus subroutines)
# which are the drive cycle files the user uploaded.
    if not dc_names and additional_content:
    subroutine_names = set(canonical.config.get("subroutines", {}).keys())
    dc_names = set(additional_content.keys()) - subroutine_names
verdict: slop

### 11  frontend/src/redux/slices/model/jobs-slice.ts:178
# Fetch single job
    builder
    .addCase(fetchJob.pending, (state) => {
    state.status = 'loading';
    })
verdict: ?

### 12  backend/src/simulation/services/usage_service.py:106
# Aggregation must count every log, so page past PostgREST's max_rows
# cap; ordering by id keeps pagination stable across timestamp ties.
    logs = await self.activity_log_repo.list_all_activity_logs(
    filters=filters,
    order_by="id",
    )
verdict: ?

### 13  packages/ionworkspipeline/src/ionworkspipeline/data_fits/objectives/ocp_msmr.py:988
# MSMRFullCellModel.solve doesn't emit dQ/dU directly; derive it
# from the model's native (U_full, q_full) grid then interpolate to
# the data voltage grid masked by dQdU_mask.
    U_full = sol["Full voltage [V]"]
    q_full = sol["Full capacity [A.h]"]
    dQdU_full = -np.gradient(q_full, U_full)
    dQdU_eval = interp1d(
verdict: ?

### 14  backend/src/services/organization_service.py:228
# Look up or create auth user by email, get the user id from response.
# Email case/whitespace normalization lives in UserRepository.get_user_by_email
# (Supabase Auth stores emails lowercased; the case-sensitive DB eq must
# match). Auth invite lowercases on its own.
    service_client = self.service_user_repo.supabase  # service key client
    existing_user = await self.service_user_repo.get_user_by_email(email)
    if not existing_user:
    try:
verdict: slop

### 15  backend/tests/test_routes/test_add_custom_variable.py:254
# Model already has custom var B that references A
    b_json = convert_symbol_to_json(pybamm.CoupledVariable("A"))
    model = _model_with_config(
    config={
    "pybamm_model": "SPM",
verdict: keep

### 16  packages/ionworkspipeline/src/ionworkspipeline/direct_entries/piecewise_interpolation.py:382
# Linear interpolation in this segment
    alpha = (var - bp_i) / (bp_ip1 - bp_i)
    interp_value = values[i] + (values[i + 1] - values[i]) * alpha
    H_in_segment = smooth_step(var, bp_i, smoothing) * (
    1 - smooth_step(var, bp_ip1, smoothing)
verdict: keep

### 17  backend/tests/test_services/test_anyscale_service.py:608
# --- Tests for env-var-configurable defaults ---
    class TestWorkerNodesMaxEnvOverride:
    """ANYSCALE_WORKER_NODES_MAX env var overrides DEFAULT_WORKER_NODES_MAX."""
    def test_default_value(self, monkeypatch):
verdict: slop

### 18  frontend/src/pages/dashboard/projects/settings.tsx:5
# ----------------------------------------------------------------------
    const metadata = { title: `Settings | Projects - ${CONFIG.appName}` };
    export default function Page() {
    return (
    <>
verdict: slop

### 19  backend/tests/test_jobs/test_anyscale_backend.py:313
# A job submitted before env-scoping, without a persisted id: the env-scoped
# lookup misses, so termination must retry the pre-scoping {type}-{id} name
# rather than leave expensive compute running.
    monkeypatch.setattr("src.jobs.backends.base.settings.ANYSCALE_ENV", "production")
    backend, svc = _make_backend()
    job = _job(JobType.DATA_FIT)
    job.anyscale_job_id = None
verdict: slop

### 20  backend/src/jobs/processors/simple_pipeline.py:294
# The realized pool can be smaller than requested (demand-bound
# or partial readiness); reconcile so each element's planner
# admits only as many tasks as there are healthy actors.
    capacity = reconcile_capacity_to_realized(
    capacity, executor.num_workers
    )
    head_node = get_or_create_head_node_actor()
verdict: slop

### 21  packages/ionworkspipeline/src/ionworkspipeline/calculations/particle_diffusivity.py:407
# Set options
    default_options: dict[str, iwutil.OptionSpec] = {
    "interpolator": iwutil.OptionSpec("linear", ["cubic", "pchip"]),
    "transformation": iwutil.OptionSpec("none", ["log"]),
    "scale factor": iwutil.OptionSpec(False, [True]),
verdict: ?

### 22  frontend/src/components/protocol-builder/yaml-utils.ts:422
# Handle derivative notation: d/dt(Type) op value
    const derivMatch = text.match(/^d\/dt\((\S+)\)\s*([<>]=?)\s*(.+)$/);
    if (derivMatch) {
    return {
    type: derivMatch[1] as CustomEnd['type'],
verdict: keep

### 23  backend/src/ops_tasks/0013_audit_schema_contract_breaking_keys.py:108
# Small batch: job_config JSONB can be tens of MB (embedded data arrays),
# so keep the page size low to bound memory on the audit run.
    limit = 25
    offset = 0
    scanned = 0
    findings: Counter = Counter()
verdict: keep (borderline)

### 24  frontend/src/components/protocol-builder/step-forms.tsx:594
# EISStepForm
    type EISStepWithId = EISStep & { _id: string };
    export function EISStepForm({ step, onChange, readOnly = false }: StepFormProps<EISStepWithId>) {
    return (
verdict: slop

### 25  backend/tests/test_search/conftest.py:25
# ---------------------------------------------------------------------------
    OTHER_ORG_ID = "00000000-0000-0000-0000-000000000001"
    _LOCAL_SUPABASE_URL = "http://127.0.0.1:54321"
verdict: slop

### 26  backend/src/routes/models.py:337
# Re-serialize to JSON and compress for storage
    json_bytes = json.dumps(sanitized_dict).encode("utf-8")
    compressed_data = compress_to_base64(json_bytes)
    import logging
verdict: slop

### 27  frontend/src/components/nav-section/horizontal/nav-section-horizontal.tsx:67
# ----------------------------------------------------------------------
    function Group({
    items,
    render,
    cssVars,
verdict: slop

### 28  backend/src/jobs/plot_data.py:357
# Parsed metadata blobs keyed by (job_id, organization_id).
# The blob is rewritten in place while the job runs (checkpoints, then the
# final validation payload), so an entry captured mid-run can be stale. The
# 1-hour TTL is fine for the steady state; callers that need a key only present
# in the final blob (e.g. validation_plot_config) pass force_refresh=True to
# re-read storage and overwrite a stale entry rather than 404 until expiry.
    _metadata_cache: TTLCache[tuple[str, str], dict[str, Any]] = TTLCache(
    maxsize=64, ttl=3600
    )
    _metadata_cache_lock = asyncio.Lock()
verdict: slop

### 29  backend/src/repositories/optimizations.py:34
# ------------------------------------------------------------------
    def _build_select(self, filters: dict[str, Any] | None) -> str:
    """Build the select projection, switching left joins to inner joins
    when a filter targets a joined table.
    Parameters
verdict: slop

### 30  frontend/src/utils/cycle-filter-parser.test.ts:68
# "0:1:9999999" must bound its loop to existing cycles, not spin through
# millions of out-of-range indices, and must not error.
    const result = parseCycleFilter('0:1:9999999', 100);
    expect(result.error).toBeNull();
    expect(result.cycles).toHaveLength(101);
    expect(result.cycles[result.cycles.length - 1]).toBe(100);
verdict: slop

### 31  backend/src/repositories/base.py:489
# Use upsert with ignore_duplicates to handle conflicts
    response = await (
    self.supabase.table(self.table_name)
    .upsert(
    serialized_data,
verdict: keep

### 32  packages/ionworkspipeline/src/ionworkspipeline/direct_entries/electrolyte.py:298
# TDF(c, T)
    "Landesfeind electrolyte thermodynamic factor p1": -5.58,
    "Landesfeind electrolyte thermodynamic factor p2": 7.17,
    "Landesfeind electrolyte thermodynamic factor p3": 3.80e-2,
    "Landesfeind electrolyte thermodynamic factor p4": 1.91,
verdict: keep

### 33  packages/ionworkspipeline/src/ionworkspipeline/solvers/kernels.py:8
# Below this threshold for |decay * dt|, the exponential integration
# formula suffers catastrophic cancellation in (bdt - (1 - exp(-bdt))).
# The trapezoidal rule is used instead, which is the correct O(bdt²)
# Taylor expansion with relative error O(bdt²/12) < O(1e-24).
    _EXP_DEGENERATE_THRESHOLD = 1e-12
    @numba.njit(cache=True)
    def _quadrature_kernel(y_out, y0, forcing, dt, N):
    """Cumulative trapezoid for piecewise-linear forcing, in-place."""
verdict: slop - needs to be less verbose

### 34  packages/ionworkspipeline/src/ionworkspipeline/solvers/grad_codegen.py:125
# Build in a private temp dir: CodeGenerator writes fixed <stem>.c/.h names,
# so concurrent compiles of the same hash (xdist workers) would collide. The
# finished .so is published to the shared cache with one atomic os.replace.
    build = tempfile.mkdtemp(dir=cdir)
    try:
    gen = casadi.CodeGenerator(stem, {"with_header": True})
    gen.add(fn)
verdict: slop

### 35  backend/tests/test_services/test_ecm.py:251
# ---------------------------------------------------------------------------
    class TestRunFit:
    @pytest.fixture()
    def synthetic_data(self):
    return _make_synthetic_data(300, with_ocv=True)
verdict: slop

### 36  frontend/src/sections/lab/channel-live-data.tsx:85
# The measurement's updated_at captured at the moment the plotted data was
# fetched. The `lastUpdate` prop polls independently (every 30s via the lab
# status query), so binding the freshness stamp to it directly would let the
# stamp advance past the snapshot actually on screen. Stamp what we drew.
    const [dataAsOf, setDataAsOf] = useState(lastUpdate);
    const [tab, setTab] = useState<TabKey>('time_series');
verdict: slop - overly verbose

### 37  frontend/src/_mock/_invoice.ts:7
# ----------------------------------------------------------------------
    export const INVOICE_STATUS_OPTIONS = [
    { value: 'paid', label: 'Paid' },
    { value: 'pending', label: 'Pending' },
    { value: 'overdue', label: 'Overdue' },
verdict: slop

### 38  backend/src/routes/cell_measurements.py:95
# --- Routers --- #
# 1) instance_context_router: mounted under
# /cell_instances/{cell_instance_id}/cell_measurements
# 2) direct_router: mounted at /cell_measurements for ID-only fetches
    instance_context_router = APIRouter(tags=["Cell Measurements"])
    direct_router = APIRouter(tags=["Cell Measurements"])
verdict: slop

### 39  backend/src/jobs/processors/simple_pipeline.py:361
# Snapshot the CPU-seconds integral (billing basis) at teardown.
    realized_core_seconds = executor.cpu_seconds
    try:
    executor.shutdown()
    except Exception as shutdown_err:
verdict: keep

### 40  frontend/src/sections/agent/floating-chat-widget.tsx:36
# A floating "support chat" bubble available on every dashboard page. Clicking
# it opens a single-session chat panel (no session list). Each open starts a
# fresh session; recent sessions are reachable via a small menu. The current
# page is inferred from the route and sent with every turn so the agent can
# resolve references like "this study" without the user repeating ids.
    const PANEL_WIDTH = 690;
    const PANEL_HEIGHT = 820;
verdict: slop

### 41  packages/ionworkspipeline/src/ionworkspipeline/execution/sinks.py:25
# str() eagerly: %-formatting is deferred to handler time, so a
# raising __repr__ would otherwise escape this guard entirely.
    logger.info("%s: %s", type(event).__name__, str(event))
    except Exception:  # noqa: BLE001, S110 — sinks must not break the fit
    pass
    class ListSink:
verdict: keep

### 42  frontend/src/hooks/measurements/useMeasurementFilters.ts:6
# State
    cycleFilterValue: string;
    cycleFilterError: string | null;
    appliedCycleCounts: number[] | undefined;
    stepFilterValue: string;
verdict: keep

### 43  backend/src/jobs/plot_data.py:146
# Upload all plots. Track successful paths so that on failure an operator
# knows which files to clean up (orphaned — not referenced by any manifest
# since we only write the manifest after all uploads succeed).
    uploaded: list[str] = []
    for path, data, objective_name, idx in upload_queue:
    try:
    upload_file_to_storage(supabase_service, path, data, _PLOT_STORAGE_BUCKET)
verdict: slop

### 44  frontend/src/sections/agent/stream-agent.ts:252
# Best-effort stop: the client-side abort already stopped the UI. Without a
# session there is nothing to authenticate the server-side stop with.
    return;
    }
    const orgId = store.getState().controller.user.organizationId;
    await fetch(`${CONFIG.agentUrl}/agent/stop/${encodeURIComponent(conversationId)}`, {
verdict: keep - but slightly verbose

### 45  backend/tests/test_services/test_ecm.py:155
# _sort_interp_ocv
    class TestSortInterpOcv:
    def test_monotonic_input(self):
    soc = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
verdict: slop

### 46  packages/ionworkspipeline/src/ionworkspipeline/parsers/calculations.py:72
# Schemas with positional ``__init__`` overrides raise TypeError when a
# required field is omitted, and Pydantic raises ValidationError on
# type mismatch / extra-field violations. Re-raise both as
# ConfigurationError so callers see a single, consistent validation
# failure type — same contract as parse_objectives and parse_cost.
    raise UserConfigurationError(
    f"Invalid configuration for calculation {calculation_type!r}: {e}"
    ) from e
    return runtime_cls.from_schema(schema)
verdict: slop - overly verbose

### 47  backend/src/simulation/services/simulation_service.py:629
# Create batch mappings for all simulations
# Let the database handle conflicts with ignore_duplicates=True
    mapping_data_list = [
    CreateStudySimulationMapping(
    study_id=study_id,
    simulation_id=str(simulation_id),
verdict: slop

### 48  frontend/src/sections/lab/lab-wall-container.tsx:214
# In table view, grow to fill the dashboard content column so the
# grid can take the remaining viewport height (the filter + summary
# cards keep their natural height; the table absorbs the rest). In
# card view, stay natural-height and let the page scroll.
    ...(view === 'table' && { flex: 1, minHeight: 0 }),
    }}
    >
    {/* One control row, read left-to-right as two zones: filters (Site,
verdict: slop

### 49  frontend/src/redux/utils/convert-table-filter-base.test.ts:299
# The measurements grid offers contains/startsWith/endsWith on all three id
# columns. They are uuid columns, so a pattern has to be redirected to the
# generated text mirror or the query errors in the database.
    it.each([
    ['id', 'id_text'],
    ['cell_instance_id', 'cell_instance_id_text'],
    ['spec_id', 'spec_id_text'],
verdict: ?

### 50  frontend/src/components/nav-section/horizontal/nav-item.tsx:16
# ----------------------------------------------------------------------
    export const NavItem = forwardRef<HTMLButtonElement, NavItemProps>((props, ref) => {
    const {
    path,
    icon,
verdict: slop

### 51  backend/tests/test_utils/test_data_conversion.py:591
# Test 2: Filter with x_max only
    result = convert_time_series_bytes_to_dict(parquet_bytes, x_max=3.0)
    assert result["Time [s]"] == [0.0, 1.0, 2.0, 3.0]
    assert result["Voltage [V]"] == [3.7, 3.8, 3.9, 4.0]
    result = convert_time_series_bytes_to_dict(parquet_bytes, x_min=1.0, x_max=4.0)
verdict: slop

### 52  packages/ionworkspipeline/src/ionworkspipeline/data_fits/models/single_electrode_lumped_spmr.py:549
# Legend
    leg = ax.legend(loc="center left", bbox_to_anchor=(1.05, 0.5), frameon=True)
    leg.get_frame().set_edgecolor("k")
    if fig is not None:
    fig.tight_layout()
verdict: slop

### 53  backend/tests/test_services/test_anyscale_service.py:20
# --- Fixtures ---
    @pytest.fixture
    def anyscale_service() -> AnyscaleService:
    """Provides an AnyscaleService with a mock Supabase client."""
    with patch("src.services.anyscale_service.get_supabase_service_client"):
verdict: slop

### 54  backend/src/services/ecm.py:593
# Estimate capacity from coulomb counting unless the caller opted in to
# fitting it (ocv_soc_curve AND bounds_capacity). Passing est_cap here rather
# than leaving it None for the fitter to re-derive keeps this per-segment
# estimate; the fitter's own fallback is a whole-trace count that overcounts
# multi-segment traces.
    fitting_capacity = ocv_soc_curve is not None and bounds_capacity is not None
    if capacity is None and not fitting_capacity:
    capacity = est_cap
    schedule = (
verdict: slop

### 55  frontend/src/sections/optimization/optimization-new-with-template-container.tsx:285
# Pattern to match escaped quotes around input parameters in any field
# (value, ends, duration, etc.)
# Handle both single and double escaped quotes
    let result = experiment;
    result = result.replace(/\\"input\[([^\]]+)\]\\"/g, '"input[$1]"');
    result = result.replace(/\\\\"input\[([^\]]+)\]\\\\"/g, '"input[$1]"');
    return result;
verdict: ?

### 56  backend/tests/test_services/test_cell_measurements.py:1121
# Enumeration must run before the cascade-triggering DB delete.
    assert calls == ["list_ids", "db_delete"]
    @pytest.mark.asyncio
    async def test_delete_measurement_no_analyses_skips_sweep(
    cell_measurement_service: CellMeasurementService,
verdict: keep

### 57  backend/src/services/pipeline_service.py:1362
# Capture the running jobs BEFORE the bulk status write — afterwards the
# elements are CANCELED and can no longer be found by RUNNING status.
    running_job_ids = [
    element.job_id
    for element in elements
    if element.job_id and element.status == PipelineElementStatus.RUNNING
verdict: keep

### 58  backend/src/jobs/worker.py:287
# Load params and metadata from storage when available
    callback_url = job.callback_url
    params_path = job.params_path
    metadata_path = job.metadata_path
    params = {}
verdict: slop

### 59  backend/tests/test_utils/test_data_conversion.py:158
# Initialize using aliases as required by MeasurementStep
    steps_list_with_none = [
    MeasurementStepBase(
    **{
    "Step from cycler": 1,
verdict: slop

### 60  backend/src/repositories/planned_measurements.py:22
# planned_measurements has two FKs to users (requested_by, scheduled_by), so
# a bare `users(email)` embed is ambiguous (PostgREST PGRST201). Pin each FK
# under its own alias so both the requester and scheduler emails come back;
# the PlannedMeasurement model flattens them onto requested_by_email /
# scheduled_by_email (so the base repository's users-join is not used here).
    _USER_EMBED = (
    "requester:users!planned_measurements_requested_by_fkey(email), "
    "scheduler:users!planned_measurements_scheduled_by_fkey(email)"
    )
verdict: slop

### 61  frontend/src/components/protocol-builder/step-forms.tsx:593
# ============================================================================
    type EISStepWithId = EISStep & { _id: string };
    export function EISStepForm({ step, onChange, readOnly = false }: StepFormProps<EISStepWithId>) {
verdict: slop

### 62  backend/tests/test_repositories/test_planned_measurements_repository.py:93
# planned_measurements has two FKs to channels (channel_id and the
# composite channel_id+project_id), so a bare `channels(...)` embed is
# ambiguous (PGRST201 -> 500). The embed must pin the single-column FK.
    repo = _make_repo()
    repo.get = AsyncMock(return_value=None)
    await repo.get_planned_measurement("pm-1")
    columns = repo.get.await_args[0][1]
verdict: slop

### 63  backend/src/services/ecm_fit_jobs.py:412
# Filter by an inclusive [start_step, end_step] range on "Step count".
# Using x_min/x_max (a real range predicate) rather than enumerating
# ``step_counts`` avoids an arbitrary upper ceiling that would silently
# truncate measurements with more steps than the ceiling. ``None`` on
# either bound means "open" (from the first / to the last step).
    ts_results = await asyncio.gather(
    *[
    self.measurement_service.get_time_series(
    organization_id=organization_id,
verdict: slop

### 64  backend/tests/test_jobs/test_preflight_sizing.py:260
# Patience == iteration cap disables early stop, so the run does the full
# 2000 gens; the sane clamp must not truncate it (else a fit that should
# scale is sized head-only — the full_pipeline DFN + DE regression).
    cfg = {
    "optimizer": {
    "type": "DifferentialEvolution",
    "max_iterations": 2000,
verdict: slop

### 65  frontend/src/redux/utils/convert-table-filter-base.test.ts:393
# This test documents which filter params the backend
# /cell_measurements/by-project/{project_id} endpoint accepts.
# If a converter produces a param not in this set, the backend
# silently ignores it — the filter appears to work but doesn't.
    const ACCEPTED_PARAMS = new Set([
    'id',
    'name',
    'created_by_email',
verdict: ?

### 66  backend/src/services/optimization_service.py:233
# Get single optimization
    async def get_optimization(
    self,
    *,
    id: str,
verdict: slop

### 67  backend/src/jobs/execution_capacity.py:640
# Array children share only the parameter spec, so the first-child probe
# can't prove homogeneity — only a single fit is eligible for head-only.
    if n_elements == 1:
    w_head = max(1, min(constants.head_worker_cpus, width))
    waves_head = math.ceil(width / w_head)
    wall_head = t_build + n_gen * waves_head * t_solve
verdict: keep

### 68  backend/src/simulation/services/model_service.py:751
# The ECM now exposes Anode/Cathode potential [V] natively
# (computed from a configurable overpotential split, with the
# half-cell parameter sets assigning all overpotential to the
# working electrode so Cathode potential ≡ Voltage). No
# backend-side aliasing needed.
    elif ModelService._get_model_chemistry(parameterized_model) in (
    "lithium_sulfur",
    "generic",
    ):
verdict: slop

### 69  backend/src/repositories/search.py:445
# Subset of PostgreSQL's default English stop words that are likely to appear
# in user queries.  Tokens matching these are dropped before building the
# tsquery so that queries like "the battery" don't produce an invalid
# to_tsquery expression ("the:*" is a syntax error after stop-word removal).
    _STOP_WORDS: frozenset[str] = frozenset(
    "a an and are as at be by for from has he her him his how i "
    "in is it its me my of on or our she that the their them they "
    "this to us was we were will with you your".split()
verdict: slop - overly verbose

### 70  frontend/src/components/parameterized-model/parameterized-model-create-form.tsx:296
# Only set parameterType to 'Library' on initial load, not on subsequent changes
# Don't override if:
# 1. Creating from pipeline
# 2. ParameterType was set from search params (e.g., Clone)
# 3. We've already initialized it (user may have changed it)
    if (!isFromPipeline && !parameterTypeFromSearchParamRef && !hasInitializedParameterType) {
    methods.setValue('parameterType', 'Library');
    setHasInitializedParameterType(true);
    }
verdict: ?

### 71  frontend/src/lib/axios.ts:87
# A caller-provided X-Organization-Id wins over the ambient store value —
# callers that receive an explicit organizationId (e.g. models-api's
# orgHeaders) must not depend on store timing or be clobbered during org
# switches.
    if (!(config.headers as any)['X-Organization-Id']) {
    const orgId = store.getState().controller.user.organizationId;
    if (orgId) {
    (config.headers as any)['X-Organization-Id'] = orgId;
verdict: slop

### 72  frontend/src/sections/cell/measurement-details-container.tsx:145
# X-axis options derived from the measurement's time_series columns.
    const availableXAxisOptions = useMemo(
    () => computeAvailableXAxisOptions(measurement),
    [measurement]
    );
verdict: ?

### 73  frontend/src/components/parameterized-model/parameterized-model-selector.tsx:72
# The list and single-model queries are mutually exclusive (gated on
# `readOnly`), so the sources never need merging — pick the one that's live.
    const { entities, ids } = useMemo(() => {
    const items =
    parameterizedModelsOverride ?? listPage?.items ?? (singleModel ? [singleModel] : []);
    return { entities: indexById(items), ids: items.map((pm) => pm.id) };
verdict: ?

### 74  frontend/src/components/parameterized-model/parameterized-model-create-form.tsx:220
# Check if there are any cloneable parameterized models available.
# Iterate `ids` (the current project-scoped query result) rather than
# `Object.values(entities)`: with a shared entity cache, `entities` can hold
# models from other projects the user visited earlier, whereas `ids` is
# authoritative for the models actually returned for this project.
    const hasCloneableModels = useMemo(() => {
    const currentModels = parameterizedModelIds
    .map((id) => parameterizedModelEntities[id])
    .filter(Boolean);
verdict: slop

### 75  backend/src/services/cell_specification_service.py:705
# Sweep nested analysis parquets (not covered by the folder
# delete) before the spec delete cascades the analysis rows
# out of reach. Kept OUT of the try above so a folder-delete
# failure cannot skip it; the helper is itself best-effort.
    await sweep_measurement_analysis_storage(
    self.analysis_repo,
    self.analysis_bucket_repo,
    measurement.organization_id,
verdict: slop

### 76  packages/ionworkspipeline/src/ionworkspipeline/data_fits/objectives/pulse.py:583
# Fit rest square root (ICI)
    (U0_ici, slope_ici), (t_ici, U_ici) = _bracketed_fit(
    step["Time [s]"].to_numpy(),
    step["Overpotential [mV]"].to_numpy(),
    _square_root_fit_and_score,
verdict: keep

### 77  frontend/src/redux/slices/model/agent-slice.ts:166
# Flip the most recent running tool part with this name to done/error.
    for (let i = turn.parts.length - 1; i >= 0; i -= 1) {
    const part = turn.parts[i];
    if (part.type === 'tool' && part.name === event.name && part.status === 'running') {
    part.status = event.isError ? 'error' : 'done';
verdict: ?

### 78  backend/src/routes/discovery.py:933
# Other backend failures (NotFoundError, ExternalServiceError, ...) are
# real errors — propagate to the global handler.
    raise
    except Exception as exc:  # noqa: BLE001 — surface pybamm errors verbatim
    return {
    "valid": False,
verdict: ?

### 79  frontend/src/redux/types/job.ts:83
# Type for the overall job metadata object
    export interface JobMetadata {
    history?: JobMetadataHistoryEntry[];
    [key: string]: any;
    }
verdict: ?

### 80  frontend/src/utils/simulation/plot-util.tsx:153
# Default Y must be an actual metric — ignore server template default (meant for time series)
    if (metricNames.length > 0) {
    const serverMetricDefault = templatePlotOptions?.default_variable;
    if (serverMetricDefault && existingVariables.has(serverMetricDefault)) {
    options.default_variable = serverMetricDefault;
verdict: ?

### 81  backend/src/services/pipeline_service.py:1165
# 2. Clean up element job_config files uploaded to storage at creation.
# upload_file_to_storage auto-gzips .json → .json.gz, so remove that path.
    element_config_paths = [
    _element_job_config_path(pipeline_id, el.element_order) + ".gz"
    for el in elements
    if ElementType(el.element_type) in _LARGE_CONFIG_ELEMENT_TYPES
verdict: ?

### 82  backend/tests/test_services/test_ecm.py:615
# Hand back a fit with capacity ~2x the coulomb-count estimate.
    fake = {
    "_raw": {
    "rmse": 0.005,
    "V_model": voltage.copy(),
verdict: ?

### 83  backend/tests/test_services/test_simulation_solution_service.py:468
# --- Tests for ExternalServiceError wrapping of job submission ---
    @pytest.mark.asyncio
    async def test_trigger_var_eval_job_failure_wrapped_as_external_service_error(
    sim_solution_service: SimulationSolutionService,
    mock_sim_repos: dict[str, AsyncMock],
verdict: slop

### 84  packages/ionworkspipeline/src/ionworkspipeline/solvers/dae/analysis.py:173
# Step 6: Detect isolated connected components
    raw_components = _find_connected_components(n_vars, deps)
    components: list[ComponentInfo] = []
    for cid, group in enumerate(raw_components):
    rhs_idx = tuple(i for i in group if i < n_rhs)
verdict:  slop

### 85  frontend/src/auth/guard/route-access-guard.tsx:123
# Route is blocked. On a project sub-route, land on that project's cell-specs
# list (the project home) — unless cells itself is blocked, in which case fall
# through to the projects list.
    if (isProjectRoute(pathname)) {
    const match = pathname.match(/^\/dashboard\/projects\/([^/]+)/);
    const projectId = match?.[1];
    if (projectId && isRouteAllowed(navConfig, NAV_ITEM_KEYS.CELLS)) {
verdict: ?

### 86  backend/src/deps.py:143
# Async counterparts of the above pools — used by the AsyncClient in FastAPI
# request handlers.  The sync pools above are kept for Ray/Anyscale workers
# which have no event loop.
#
# Ownership assumption: supabase.AsyncClient has no aclose() / __aexit__ and
# never explicitly calls aclose() on its internal postgrest client. Although
# postgrest._async.client.aclose() would close its injected httpx session,
# that path is never triggered through normal garbage collection. These pools
# are therefore never closed by the supabase clients that borrow them, which
# is intentional — they are shared singletons that must outlive any individual
# request or supabase client instance.
    _ASYNC_HTTPX = httpx.AsyncClient(
    http2=True,
    limits=httpx.Limits(max_connections=200, max_keepalive_connections=50),
    timeout=httpx.Timeout(10.0, read=20.0),
verdict: slop

### 87  backend/tests/test_repositories/test_cell_data_bucket.py:260
# ---------------------------------------------------------------------------
    @pytest.mark.asyncio
    async def test_get_signed_measurement_urls_returns_empty_for_no_files():
    """Empty file list returns immediately without calling the storage API."""
    repo, bucket_client = _make_repo()
verdict: slop

### 88  frontend/src/redux/api/pipelines-api.ts:128
# Optimistically flip the status everywhere it is cached; roll back if
# the cancel request fails.
    onQueryStarted: async (pipelineId, { dispatch, getState, queryFulfilled }) => {
    const patches = [
    dispatch(
    pipelinesApi.util.updateQueryData('getPipeline', pipelineId, (draft) => {
verdict: ?

### 89  backend/src/routes/cell_measurements.py:403
# Removed per-measurement delete from instance context. Now served by direct router.
    @direct_router.get(
verdict: slop

### 90  frontend/src/components/parameterization/elements/hooks/useValidationPlots.ts:82
# If job is completed and has plot config, return it
    if (job.status === JobStatus.COMPLETED && plotConfig) {
    let annotated: ValidationPlotsData;
    if (plotConfig.format === PLOT_CONFIG_FORMAT_V2_FILES) {
verdict: ?

### 91  packages/ionworkspipeline/src/ionworkspipeline/validation.py:791
# Check if validation has been run
    if self.validation_results is None or self.summary_stats is None:
    raise UserConfigurationError(
    "No validation results available. Please run the validation "
    "using the run() method before exporting."
verdict: slop

### 92  frontend/src/hooks/measurements/useMeasurementFilters.ts:54
# Step condition state
    const [stepConditionValue, setStepConditionValue] = useState('');
    const [stepConditionError, setStepConditionError] = useState<string | null>(null);
    const [stepConditionLoading, setStepConditionLoading] = useState(false);
    const [stepConditionMatchMode, setStepConditionMatchMode] = useState<'step' | 'cycle'>('step');
verdict: keep

### 93  backend/tests/test_jobs/test_preflight_sizing.py:301
# cost_decomposable=True mirrors the runtime: a multi-objective
# decomposable fit fans out to one task per objective, so the sizing
# width (and the cap it produces) is the real parallel width.
    cfg = self._cfg(num_objectives=4, population=20)
    assert datafit_worker_demand(cfg, cost_decomposable=True) == 80
    def test_single_objective_floor_equals_ceiling(self):
    cfg = self._cfg(num_objectives=1, population=20)
verdict: keep

### 94  backend/tests/test_jobs/test_oncluster_sizing.py:322
# The gap the transient term closes: a solve that peaks well above the heap it
# leaves resident. Sampler peaks at 900, resident settles at 400 -> transient
# 500, so the reservation is sized on 900, not 400.
    import src.jobs.execution_capacity as ec
    class _StubSampler:
    def __init__(self, *a, **kw):
    self.peak_bytes = 900
verdict: slop

### 95  backend/src/routes/cell_instances.py:196
# created_by_email lives on the joined users table; the spec declares that
# remap so the route doesn't restate it.
    filters: dict[str, Any] = _CELL_INSTANCE_FILTERS.build(
    name=name, created_by_email=created_by_email
    )
    _CELL_INSTANCE_FILTERS.build_range(
verdict: slop

### 96  frontend/src/redux/slices/controller/user-slice.test.ts:31
# Regression: the switch endpoint is org-scoped; defaulting to the ambient
# (deactivated) org header made the deactivation gate 403 the very request
# that lets the user escape. It must carry the target org instead.
    let sentHeaders: Record<string, unknown> | undefined;
    mockAxios.onPatch('/users/me/active-organization', ({ config }: HandlerContext) => {
    sentHeaders = config?.headers as Record<string, unknown>;
    return undefined;
verdict: ?

### 97  backend/tests/test_repositories/test_optimizations.py:42
# ===================================================================
    class TestBuildSelect:
    """Tests for ``OptimizationsRepository._build_select``."""
verdict: slop

### 98  frontend/src/theme/core/typography.ts:78
# Brand: Space Grotesk 600 for all headings, never 700/800. The lighter weight
# "keeps headings from shouting" — facts carry the argument. Applies the
# secondary (Space Grotesk) family to h4/h5 too so every heading is consistent.
    h1: {
    fontFamily: secondaryFont,
    fontWeight: baseTypography.fontWeightSemiBold,
    lineHeight: 80 / 64,
verdict: ?

### 99  frontend/src/components/nav-section/horizontal/nav-list.tsx:45
# If the pathname changes, close the menu
    if (open) {
    onClose();
    }
    }, [pathname]);
verdict: slop

### 100  backend/src/services/pipeline_service.py:497
# Submission failed. Guard against a fast callback having already
# reconciled the element to a terminal state during submission.
    current = await self.element_repo.get_by_id(element.id)
    if current is not None and (
    current.status in PipelineElementStatus.TERMINAL_STATUSES
    ):
verdict: ?

### 101  frontend/src/sections/lab/cycler-row.tsx:44
# A filter auto-opens rows so matching tiles show without a second click;
# otherwise the row honours the user's own toggle. Deriving it (rather than
# syncing an effect into state) keeps filter and toggle from fighting.
    const expanded = filter !== 'all' || manuallyExpanded;
    const subtitle = [siteName, cycler.manufacturer, cycler.model].filter(Boolean).join(' · ');
    const channels = useMemo(
    () => filterChannelsByState(cycler.channels, filter),
verdict: ?

### 102  frontend/src/redux/types/index.ts:1
# Keep common/uncertain/shared types here
    export type AsyncStatus = 'idle' | 'loading' | 'succeeded' | 'failed';
    export * from './user';
    export * from './users';
    export * from './parameterized-model';
verdict: keep

### 103  packages/ionworkspipeline/src/ionworkspipeline/data_fits/objectives/design_objective.py:518
# Apply action transformation (e.g., negate for Maximize)
    action_value = action.apply(raw_metric_value)
    weighted_value = action_value * action.weight
    outputs[name] = weighted_value
verdict: ?

### 104  frontend/src/sections/agent/chat-view.tsx:764
# Only clear the shared refs if they still point at THIS stream. On a
# session switch the switch-abort effect (and the next session's
# runStream) may already have repointed them at another live stream; a
# blind null here would clobber that stream's controller/guard.
    if (abortRef.current === controller) abortRef.current = null;
    if (streamingRef.current === sid) streamingRef.current = null;
verdict: slop - overlly verbose

### 105  frontend/src/sections/data-management/components/measurement-comparison-view.tsx:209
# Split into per-cycle segments, each starting at x=0
    const cycleSet = Array.from(new Set(cycleSlice)).sort((a, b) => a - b);
    const totalCycles = cycleSet.length;
    cycleSet.forEach((cycle, cycleIdx) => {
    const mask = cycleSlice.map((c) => c === cycle);
verdict: ?

### 106  backend/src/services/analysis_service.py:212
# Not found, or a multi-org caller passed a measurement visible to
# them in a different org than the request's active org. Refuse
# rather than write an analysis scoped to a different org than its
# parent measurement (which would misplace the row and its parquet).
    raise NotFoundError("measurement", measurement_id)
    with translate_source_fk_violation():
verdict: slop

### 107  backend/src/utils/data_conversion.py:584
# Remove helper columns if they weren't in the original request
    if columns is not None:
    final_columns = [c for c in columns if c in df.columns]
    if final_columns:
    df = df.select(final_columns)
verdict: keep

### 108  frontend/src/components/protocol-builder/form-fields.tsx:150
# ============================================================================
    interface FormRowProps {
    children: ReactNode;
    spacing?: number;
verdict: slop

### 109  frontend/src/components/snackbar/snackbar.tsx:29
# button
    actionButton: snackbarClasses.actionButton,
    cancelButton: snackbarClasses.cancelButton,
    closeButton: snackbarClasses.closeButton,
    default: snackbarClasses.default,
verdict: slop

### 110  packages/ionworkspipeline/src/ionworkspipeline/data_fits/objectives/current_driven.py:417
# Get display properties for this variable
    props = self.VARIABLE_DISPLAY_PROPERTIES.get(
    obj_var,
    {
    "display_name": obj_var,
verdict: keep

### 111  frontend/src/utils/model/parameter-formatting.ts:32
# If already an array, use as is
    if (Array.isArray(parameters)) {
    return parameters
    .filter((p) => !filterFn || filterFn(p.name))
    .map((p) => ({
verdict: slop

### 112  backend/tests/test_jobs/test_simple_pipeline_processor.py:539
# Skip the Ray/executor injection path: this test only exercises
# cost extraction from datafit.results.costs.
    patch(
    "src.jobs.processors.simple_pipeline._connect_to_ray_with_retry",
    side_effect=ConnectionError("cannot connect"),
    ),
verdict: slop - should be docstring

### 113  backend/tests/test_utils/test_design_optimization_converter.py:74
# ---------------------------------------------------------------------------
    @pytest.fixture
    def fake_parameterized_model_row():
    """A minimal SPM-backed parameterized-model row as returned by Supabase."""
    return {
verdict: slop

### 114  backend/src/services/ecm_fit_jobs.py:119
# ------------------------------------------------------------------
    async def submit_from_measurements(
    self,
    measurements: list[FitMeasurementRequest],
verdict: slop

### 115  backend/src/routes/organizations.py:42
# The service works in seconds (the unit stored in activity logs and the
# org usage_limit); this endpoint presents hours for consumers, rounding to
# avoid long floating-point tails in the response.
    _HOURS_DECIMALS = 3
    def _to_hours(seconds: float | None) -> float | None:
    if seconds is None:
    return None
verdict: slop - should be docstring

### 116  backend/src/services/pipeline_service.py:599
# DATA_FIT and VALIDATION configs can be 50MB+ (objectives blob). Pass the
# storage path so the worker downloads directly — the backend never reads it.
# DIRECT_ENTRY and CALCULATION configs are small; fetch from DB as normal.
    use_storage_path = element_type in _LARGE_CONFIG_ELEMENT_TYPES
    job_config_path: str | None = None
    config: dict | None = None
    if use_storage_path:
verdict: slop

### 117  backend/tests/test_routes/test_parameterized_models.py:513
# Mock to return empty list
    mocker.patch(
    "src.routes.parameterized_models.ModelService.get_scalar_variable_names",
    return_value=[],
    )
verdict: slop

### 118  backend/src/jobs/ray_executor.py:366
# ctx id -> shared object-store ref (ray.put of the context, once).
    self._context_refs: dict[int, ray.ObjectRef] = {}
    self._pending: dict[ray.ObjectRef, tuple[TaskTag, _Worker]] = {}
    self._dead_letter: list[TaskResult] = []
verdict: slop - not useful

### 119  frontend/src/redux/api/studies-api.ts:19
# Backend hard-caps the project studies list at le=100; the sidebar shows the
# whole (uncapped-in-practice) list with no pagination UI. The container needs
# `total` to tell a "complete" page from one that may be truncated, so the
# query keeps it alongside the rows rather than the caller re-deriving the cap.
    const STUDIES_LIST_LIMIT = 100;
    interface StudiesPageResponse {
    items: Study[];
    count: number;
verdict: ?

### 120  backend/tests/test_sources.py:91
# ---------------------------------------------------------------------------
    def test_assert_single_source_none_ok():
    assert_single_source({f: None for f in SOURCE_FK_FIELDS})
verdict: slop

### 121  backend/src/parameter_library/nmc_half_cell.py:61
# Update with capacity and esoh parameters
    capacity_esoh_parameters = get_capacity_esoh_parameters(parameter_values)
    parameter_values.update(capacity_esoh_parameters, check_already_exists=False)
    return dict(parameter_values)
verdict: keep

### 122  frontend/src/utils/format-time.ts:255
# ----------------------------------------------------------------------
    /**
    * @output 2024-05-28T05:55:31+00:00
    */
    export type DurationProps = {
verdict: slop

### 123  frontend/src/sections/lab/schedule-planned-measurement-dialog.tsx:104
# Rescheduling an already-scheduled test: prefill its current channel and
# start so the scheduler tweaks rather than re-enters. A fresh (requested)
# test starts empty and the next-free-slot effect fills the start.
    const prefilledStart = planned?.planned_start_time
    ? toDatetimeLocal(new Date(planned.planned_start_time))
    : '';
    autoFilledStartRef.current = ''; // the prefill is user-owned, not auto
verdict: ?

### 124  frontend/src/hooks/measurements/useMeasurementFilters.ts:104
# Parse step conditions and get matching step counts
# This would need access to the steps data from the measurement
# For now, we'll just store the condition value
# The actual filtering will be done by the component that has access to the data
    try {
    const conditionRegex = /^[A-Za-z\s]+$/;
    if (!conditionRegex.test(stepConditionValue)) {
    throw new Error('Invalid step condition format');
verdict: ?

### 125  backend/tests/test_simulation/test_doe_service.py:27
# 2 * 3 * 5 = 30
    assert len(result) == 30
    assert any(r["a"] == 1.0 and r["b"] == 0.5 and r["c"] == 0.0 for r in result)
verdict: slop

### 126  frontend/src/components/protocol-builder/end-condition-editor.tsx:16
# ============================================================================
    const DERIVATIVE_OPTIONS = [
    { value: '0', label: 'Value (0th derivative)' },
    { value: '1', label: 'Rate of change (1st derivative)' },
    ];
verdict: slop

### 127  frontend/src/utils/simulation/simulation-list-util.tsx:194
# Filter for design parameters that are not experiment parameters or metrics
# Filter for design parameters that actually vary
    const varyingDesignParametersKeys = Array.from(designParameterCandidates)
    .filter((key) => !experimentParameters.has(key) && !metrics.has(key))
    .filter((key) => designParameterValues[key]?.size > 1);
    return {
verdict: slop

### 128  backend/src/pydantic_models/elements.py:36
# If value is not found in aliases or is not a string,
# let the default Enum behavior raise ValueError.
# Returning None here tells the Enum constructor that the value couldn't be
# found.
    return None
    class ElementSubtype(StrEnum):
    HALF_CELL_OCP = "Half Cell OCP"
verdict: slop - should be docstring

### 129  backend/src/routes/cyclers.py:107
# The owning project must belong to the selected org, else a caller could
# attach a cycler to another org's project (the composite FK would reject it
# at the DB, but a clean 404 is better than a driver error).
    project = await project_repo.get_by_id(cycler_data.project_id)
    if project is None or project.organization_id != organization_id:
    raise NotFoundError("project", cycler_data.project_id)
    create_dict = cycler_data.model_dump()
verdict: slop

### 130  frontend/src/theme/core/components/card.tsx:10
# Mintlify-style: white card on the grey page, lifted by a hairline border
# plus a soft shadow. Brand card radius is 6px (sharp = engineering tool),
# not the template's doubled 12px.
    root: ({ theme }) => ({
    position: 'relative',
    border: `1px solid ${varAlpha(theme.vars.palette.grey['500Channel'], 0.16)}`,
    boxShadow: `var(--card-shadow, 0 1px 2px 0 ${varAlpha(theme.vars.palette.grey['900Channel'], 0.04)}, 0 4px 12px -4px ${varAlpha(theme.vars.palette.grey['900Channel'], 0.06)})`,
verdict: ?

### 131  frontend/src/theme/core/components/dialog.tsx:6
# ▼▼▼▼▼▼▼▼ 🎨 STYLE ▼▼▼▼▼▼▼▼
    styleOverrides: {
    paper: {
    variants: [
    {
verdict: ?

### 132  packages/ionworkspipeline/src/ionworkspipeline/parsers/models.py:157
# ``simulation_settings`` (persistent mesh + solver) may ride on a model config
# emitted by the schema model classes' to_config(). The model itself does not
# consume it — settings are resolved and folded into simulation_kwargs at
# simulation/objective build time — so drop it here rather than pass it to a
# model constructor that would reject the unexpected kwarg. (Copy, don't mutate
# the caller's dict.)
    if "simulation_settings" in config:
    config = {k: v for k, v in config.items() if k != "simulation_settings"}
    if config["type"] == "custom":
verdict: slop

### 133  frontend/src/sections/lab/channel-live-data.tsx:109
# Latest `lastUpdate` without making it a fetchData dependency (a poll must
# not trigger a refetch). Read at fetch time to stamp the loaded snapshot.
    const lastUpdateRef = useRef(lastUpdate);
    lastUpdateRef.current = lastUpdate;
    const fetchData = useCallback(
    async (windowDays: number) => {
verdict: ?

### 134  backend/src/repositories/base.py:424
# Include the postgrest ``message`` (which names the violated
# constraint, e.g. ``..._source_pipeline_id_fkey``) plus
# ``details`` so callers that translate specific FK violations
# can identify the column/target even when one part omits it.
    fk_msg = getattr(insert_error, "message", None) or ""
    fk_detail = getattr(insert_error, "details", None) or ""
    raise BadRequestError(
    f"Invalid reference: a related record does not exist "
verdict: slop

### 135  backend/src/jobs/processors/pipeline.py:1354
# Objectives that don't support validation (e.g. Pulse) raise a
# "does not support validation" error inside validation.run(), which
# surfaces here as a partial failure with no results. Treat that as
# "not supported" so callers/UI get a clear message instead of the
# confusing "No validation results available" error that plot-config
# generation would otherwise raise.
    if (
    not validation.validation_results
    and validation_error
    and ("does not support validation" in validation_error)
verdict: slop - overly verbose

### 136  frontend/src/utils/optimizations/optimization-utils.ts:404
# Fallback: return empty array if experiment is neither string nor array
    return [];
    }
verdict: keep

### 137  frontend/src/redux/slices/model/simulations-slice.ts:443
# Handle deleteSimulation
    builder.addCase(deleteSimulation.fulfilled, (state, action) => {
    const simulationId = action.payload.simulationId;
    delete state.entities[simulationId];
    delete state.dataLoadedAt[simulationId];
verdict: keep

### 138  frontend/src/redux/api/lab-api.ts:147
# Refetch the wall (channel may move stale/occupied -> free) and, if we
# came from a channel detail page, that channel's history.
    invalidatesTags: invalidateOnSuccess(
    ({ projectId, channelId }: { projectId: string; channelId?: string }) => [
    { type: 'LabStatus', id: projectId },
    ...(channelId ? [{ type: 'ChannelMeasurements' as const, id: channelId }] : []),
verdict: ?

### 139  packages/ionworkspipeline/src/ionworkspipeline/data_fits/objectives/base_objective.py:331
# Add cost if present
    if hasattr(self, "_cost") and self._cost is not None:
    try:
    config["cost"] = reverse_parse_cost(self._cost)
    except Exception as e:
verdict: slop

### 140  backend/tests/test_repositories/test_raw_data_repository.py:286
# ---------------------------------------------------------------------------
    @pytest.mark.asyncio
    async def test_list_measurement_ids_for_raw_data_returns_plain_ids():
    repo = _make_repo()
    _wire_join_select(
verdict: slop

### 141  backend/tests/conftest.py:21
# Disable Ray 2.55's in-process uv-run runtime-env rebuild. Without this, a
# pytest-xdist worker that imports ray transitively (e.g. via
# src.jobs.processors.pipeline) before collecting the Ray test modules will
# install the uv-run hook too early, causing actor workers to fail rebuilding
# the monorepo's workspace sources. Test-environment only — production
# connects to a real cluster that is started separately and is unaffected.
    os.environ.setdefault("RAY_ENABLE_UV_RUN_RUNTIME_ENV", "0")
    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../src")))
verdict: slop

### 142  backend/src/services/pipeline_service.py:1685
# Get pipeline metadata (fast, no elements)
    pipeline = await self.get_pipeline(pipeline_id=pipeline_id)
    if pipeline.status == PipelineStatus.FAILED:
    error_detail = (
    pipeline.error or "Pipeline execution failed with an unknown error."
verdict: keep

### 143  packages/ionworkspipeline/src/ionworkspipeline/util.py:322
# check if there's any variable portion; if not, just a normal string
    if "{" in left or "{" in right:
    return f'f"{left}{right}"'
    else:
    return f'"{left}{right}"'
verdict: ?

### 144  frontend/src/components/nav-section/mini/nav-item.tsx:113
# ----------------------------------------------------------------------
    type StyledState = Pick<NavItemProps, 'open' | 'active' | 'disabled'> & {
    variant: 'rootItem' | 'subItem';
    };
    const shouldForwardProp = (prop: string) =>
verdict: slop

### 145  packages/ionworkspipeline/src/ionworkspipeline/data_fits/data_fit.py:2435
# convert to a single dictionary of new parameter values
# the keys are the parameter names
# the values are 2-row arrays, where the first row is the independent variable
# values (same for all parameters)
# and the second row is the new parameter values for the corresponding
# independent variable value
# Keys are normalised to float by _set_objectives; dtype=float keeps the
# independent-variable row numeric (the parser passes them as strings).
    ordered_keys = list(new_parameter_values_dict.keys())
    independent_variable_values = np.array(ordered_keys, dtype=float)
    first_params = new_parameter_values_dict[ordered_keys[0]]
    new_parameter_values = {}
verdict: slop

### 146  backend/tests/test_jobs/test_resubmit_job.py:44
# ---------------------------------------------------------------------------
    class TestSubmitJobMarkAsSubmissionFailed:
    """submit_job calls repo.mark_submission_failed when the backend raises."""
verdict: slop

### 147  backend/src/utils/data_conversion.py:114
# Find step boundaries (indices where step count changes)
    step_changes = np.where(np.diff(step_counts) != 0)[0]
    first_indices = np.concatenate([[0], step_changes + 1])
verdict: keep

### 148  packages/ionworkspipeline/src/ionworkspipeline/validation.py:883
# No runtime counterpart with from_schema — pass the schema through.
    return value
verdict: keep

### 149  backend/tests/test_services/test_calculation_evaluator.py:121
# ---- Tests for new metric config dict format ----
    def _make_polars_df() -> pl.DataFrame:
    """Create a Polars DataFrame for metric config evaluator tests."""
    return pl.DataFrame(
    {
verdict: slop

### 150  frontend/src/utils/simulation/simulation-list-util.tsx:854
# Check for time series: storage_folder indicates parquet files are available,
# or simulation_data.time_series contains data (legacy format before storage migration)
    const hasTimeSeries =
    templateSupportsTimeSeries &&
    simulations.some(
    (simulation) =>
verdict: keep

### 151  backend/src/jobs/processors/pipeline.py:227
# Returned by validate() when an objective type does not support validation
# plotting (no prepare_validation_results), so callers/UI can show a clear
# message instead of failing. Copy before returning — callers may mutate it.
    VALIDATION_NOT_SUPPORTED_RESULT: dict[str, Any] = {
    "validation_not_supported": True,
    "message": "Validation plots are not supported for this objective type.",
    }
verdict: ?

### 152  packages/ionworkspipeline/src/ionworkspipeline/parsers/schemas/data.py:40
# Data can be:
# - pd.DataFrame (checked at runtime, not here)
# - dict with "time_series" and/or "steps" (for DataLoader)
# - dict representing a DataFrame (from to_dict())
# - str starting with "file:", "folder:", or "db:"
    if isinstance(data, dict):
verdict: slop - should be docstring

### 153  frontend/src/sections/ecm-fitting/ecm-fitting-container.tsx:439
# Warm the RTK Query cache so the detail page mounts with data ready —
# otherwise the fresh-nav path shows "Loading model details..." until
# the user refreshes. `subscribe: false` makes this a fire-and-forget
# prefetch that doesn't hold a dangling cache subscription (the detail
# page's own hooks own the subscription once it mounts). The save has
# already succeeded, so a failed prefetch must not block navigation or
# surface as a save error — the detail page will just fetch on mount.
    await Promise.all([
    dispatch(
    parameterizedModelsApi.endpoints.getParameterizedModel.initiate(pmId, {
    subscribe: false,
verdict: slop

### 154  backend/tests/test_jobs/test_pipeline_processor_collapse.py:374
# demand=7, supply=4 → 4 workers (supply caps)
    datafit = _stub_datafit(num_jobs=7, max_useful_workers=7)
    ray_executor, _ = _run_process(
    processor, make_datafit_params, datafit=datafit, capacity=capacity
    )
verdict: keep

### 155  packages/ionworkspipeline/src/ionworkspipeline/data_fits/cost_logger.py:1011
# Checkpoint with per-iteration values and cumulative best
    if self.checkpoint_function is not None:
    checkpoint_data = {
    "best_cost": self.log_best.get("cost", best_log_in_batch["cost"]),
    "cost": best_log_in_batch["cost"],
verdict: keep

### 156  packages/ionworkspipeline/src/ionworkspipeline/execution/coordinator.py:329
# The executor can briefly report no in-flight tasks while our point
# counter is still positive; throttle and re-poll until they reconcile.
    time.sleep(min(0.01, self._poll_seconds))
    continue
    handle = self._evaluator.on_task_result(task_result)
    if handle is None:
verdict: keep

### 157  frontend/src/sections/agent/chat-view.tsx:963
# If this mount is already streaming this session (send() just created it
# and started a turn), we already hold the live messages. Refetching history
# here races the stream: the GET is issued before the assistant turn is
# persisted, and when it resolves after the turn ends — the reducer's guard
# only holds while `running` is true — its stale, assistant-less history
# clobbers the freshly streamed turn (blanking the reply and skipping its
# persist). Only (re)load + reconnect when we are NOT the one streaming it:
# a fresh mount, a hard reload, or a switch to a different session.
    if (streamingRef.current === sessionId) return;
    void (async () => {
    try {
verdict: slop

### 158  frontend/src/sections/lab/planning-container.tsx:311
# Copy is available for any status. It opens the request form
# prefilled from this row (nothing is created until the user submits);
# the copy always starts fresh in the backlog as `requested`.
    if (projectId) {
    actions.push(
    <CustomGridActionsCellItem
    key="copy"
verdict: ?

### 159  frontend/src/components/parameterized-model/parameterized-model-parameter-validator.tsx:163
# Call the onParametersUpdate callback with the updated parameters
    onParametersUpdate?.(updatedParameters);
    },
    [parameters, onParametersUpdate]
    );
verdict: ?

### 160  frontend/src/components/loading-screen/organization-deactivated-screen.tsx:32
# The deactivated org is still in the user's own membership list (deactivation
# is a soft flag, not a removal), so naming it here discloses nothing they
# didn't already know as a member — it just disambiguates which org to
# contact when they belong to several.
    const deactivatedOrgName = (organizations ?? []).find((org) => org.id === organizationId)?.name;
    const [targetOrgId, setTargetOrgId] = useState<string>('');
    const [retrying, setRetrying] = useState(false);
    const handleSwitch = () => {
verdict: slop
