The platform for continuously improving AI agents.
Write native comparison files whole and keep connector imports on settings changes (#351)
Freyam Mehta09ac9ae1deb8
diff --git a/overbae/api/views.py b/overbae/api/views.pyindex c2fd546b..07f46517 100644--- a/overbae/api/views.py+++ b/overbae/api/views.py@@ -1742,9 +1742,6 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):credential,**config_kwargs,)- from overbae.services.connectors.sync import reset_connector_import-- reset_connector_import(credential)return Response({"version": config.version,diff --git a/overbae/services/connectors/feedforward.py b/overbae/services/connectors/feedforward.pyindex 596e14bf..1758ec55 100644--- a/overbae/services/connectors/feedforward.py+++ b/overbae/services/connectors/feedforward.py@@ -6,6 +6,8 @@ from typing import Anyfrom django.utils import timezone+from overbae.services.connectors.sync import restart_connector_import+_UNSET = object()@@ -18,7 +20,8 @@ def save_sync_config(backfill_from: Any = _UNSET,backfill_to: Any = _UNSET,) -> Any:- """Create the next config version. Returns the new ConnectorSyncConfig."""+ """Create the next config version and restart the import for it. Returns the new+ ConnectorSyncConfig."""from overbae.models import ConnectorSyncConfigprev = credential.active_config()@@ -40,7 +43,13 @@ def save_sync_config(effective_from=timezone.now(),)- if prev is None and credential.auto_sync_enabled:+ if prev is not None:+ # Each save compares with the version it replaced, so concurrent saves still see+ # a source change.+ restart_connector_import(+ credential, source_changed=config.source_project_id != prev.source_project_id+ )+ elif credential.auto_sync_enabled:# First config + auto-sync: kick a normal backfill.from overbae.tasks.connector_sync import sync_connector_chunkdiff --git a/overbae/services/connectors/sync.py b/overbae/services/connectors/sync.pyindex a6bf37c3..ec53fa43 100644--- a/overbae/services/connectors/sync.py+++ b/overbae/services/connectors/sync.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import uuidfrom django.db.models import Q@@ -47,9 +48,9 @@ def connector_imported_spans(credential):return Span.objects.filter(span_id__in=ids)-def reset_connector_import(credential, *, release=True) -> int:- """Delete this credential's imported spans and rewind its sync cursor. A running- chunk passes ``release=False`` to keep holding ``next_poll_at``, its lease."""+def reset_connector_import(credential) -> int:+ """Delete this credential's imported spans and rewind its sync cursor. Only the running+ chunk calls this, so ``next_poll_at``, its lease, stays as it is."""from overbae.models import ConnectorCredentialspans = connector_imported_spans(credential)@@ -63,18 +64,41 @@ def reset_connector_import(credential, *, release=True) -> int:backfill_imported=0,backfill_total=None,sync_error="",- **({"next_poll_at": None} if release else {}),)credential.refresh_from_db()return count+# Any stored key other than the live one makes the next chunk recarve under its lease.+# Each save writes its own marker, so a chunk adopting the key cannot erase a later one.+SOURCE_CHANGED = "source-changed"+++def restart_connector_import(credential, *, source_changed: bool) -> None:+ """After new settings, import the configured range again. Spans from the same source+ project stay, since the import upserts them. Spans from a previous source project are+ removed by the next chunk, so two sources never mix in one project."""+ from overbae.models import ConnectorCredential++ ConnectorCredential.objects.filter(pk=credential.pk).update(+ sync_cursor={},+ sync_status=ConnectorCredential.SyncStatus.IDLE,+ sync_error="",+ next_poll_at=None,+ **(+ {"imported_boundary_key": f"{SOURCE_CHANGED}:{uuid.uuid4().hex}"}+ if source_changed+ else {}+ ),+ )++def prepare_connector_sync(credential) -> bool:"""Adopt or recarve so this sync uses the live mapping.names as trace roots.An empty stored key is first-seen: adopt without wiping. A changed source or- names set wipes imported spans because incremental upsert would keep the old- grouping. Assignments-only changes do not recarve.+ names set, or a changed source project, wipes imported spans because incremental+ upsert would keep the old grouping. Assignments-only changes do not recarve."""from overbae.models import ConnectorCredential@@ -82,9 +106,11 @@ def prepare_connector_sync(credential) -> bool:stored = credential.imported_boundary_key or ""recarving = bool(stored) and stored != currentif recarving:- reset_connector_import(credential, release=False)- if stored != current:- ConnectorCredential.objects.filter(pk=credential.pk).update(imported_boundary_key=current)+ reset_connector_import(credential)+ # A source change saved since the read keeps its marker, so the next chunk recarves.+ if stored != current and ConnectorCredential.objects.filter(+ pk=credential.pk, imported_boundary_key=stored+ ).update(imported_boundary_key=current):credential.imported_boundary_key = currentreturn recarvingdiff --git a/overbae/services/decision_providers.py b/overbae/services/decision_providers.pyindex c2e74f88..057c8a63 100644--- a/overbae/services/decision_providers.py+++ b/overbae/services/decision_providers.py@@ -451,8 +451,10 @@ def external_step(plan, role, participant):output_path = source.parent / f"{participant['key']}.jsonl"failures_path = output_path.with_suffix(".failures.jsonl")with (- output_path.with_suffix(".partial").open("w") as output,- failures_path.with_suffix(".partial").open("w") as failures,+ evaluation_inputs.replacing(output_path) as written,+ evaluation_inputs.replacing(failures_path) as failed,+ written.open("w") as output,+ failed.open("w") as failures,):for batch in evaluation_inputs.batches(source):saved = {@@ -481,8 +483,6 @@ def external_step(plan, role, participant):)elif not record or record.state not in {"failed", "submission_unknown"}:raise InputValidationError("Provider collection is incomplete")- output_path.with_suffix(".partial").replace(output_path)- failures_path.with_suffix(".partial").replace(failures_path)return {"completed": completed,"decisions": offset + len(chunk),diff --git a/overbae/services/evaluation_inputs.py b/overbae/services/evaluation_inputs.pyindex 4acd87eb..6d288c19 100644--- a/overbae/services/evaluation_inputs.py+++ b/overbae/services/evaluation_inputs.py@@ -1,6 +1,7 @@import fcntlimport jsonimport tempfile+import uuidfrom contextlib import contextmanagerfrom itertools import islicefrom pathlib import Path@@ -18,6 +19,18 @@ def artifact_lock(directory):yield+@contextmanager+def replacing(path):+ """Yield a file of this attempt's own beside ``path``, then swap it in whole. An older+ attempt of the same stage may still be writing; it can never tear or mix the file."""+ temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ try:+ yield temporary+ temporary.replace(path)+ finally:+ temporary.unlink(missing_ok=True)++def index(source):destination = source.parent / "chunks"with artifact_lock(destination):diff --git a/overbae/services/mcp/tools_connectors.py b/overbae/services/mcp/tools_connectors.pyindex 2bab5462..1ec0b899 100644--- a/overbae/services/mcp/tools_connectors.py+++ b/overbae/services/mcp/tools_connectors.py@@ -647,12 +647,6 @@ def _configure_connector_sync(if creating_first and "lookback_days" not in payload.model_fields_set:config_kwargs["lookback_days"] = _FIRST_CONFIG_LOOKBACK_DAYSsave_sync_config(connector, **config_kwargs)- ConnectorCredential.objects.filter(pk=connector.pk).update(- sync_cursor={},- sync_status=ConnectorCredential.SyncStatus.IDLE,- sync_error="",- next_poll_at=None,- )connector.refresh_from_db()details = _details(context, connector)mapping_pending = _needs_mapping_approval(connector)diff --git a/overbae/services/native_evaluation.py b/overbae/services/native_evaluation.pyindex d85df1af..1d652db9 100644--- a/overbae/services/native_evaluation.py+++ b/overbae/services/native_evaluation.py@@ -41,7 +41,7 @@ from overbae.services.decision_providers import (qualify_participants,recover_request,)-from overbae.services.evaluation_inputs import artifact_lock+from overbae.services.evaluation_inputs import artifact_lock, replacingfrom overbae.services.training_release import currentlogger = logging.getLogger(__name__)@@ -598,22 +598,20 @@ def collect(plan, stage, receipt):volume = modal.Volume.from_name("overmind-sft", environment_name=plan.config["runtime"]["environment"])- partial = target.with_suffix(".partial")- with partial.open("wb") as output:- for chunk in volume.read_file(f"/decision-evaluations/{evaluation_id}/{filename}"):- output.write(chunk)- if digest_file(partial) != checksum:- raise InputValidationError("Native prediction artifact checksum differs.")- partial.replace(target)+ with replacing(target) as partial:+ with partial.open("wb") as output:+ for chunk in volume.read_file(f"/decision-evaluations/{evaluation_id}/{filename}"):+ output.write(chunk)+ if digest_file(partial) != checksum:+ raise InputValidationError("Native prediction artifact checksum differs.")if preparing:for arm in participants(plan):if (arm["kind"] != "external"and preparation_groups(plan)[arm.get("job") or arm["key"]][0] == group):- (directory(plan, role) / f"{arm['key']}.failures.jsonl").write_bytes(- target.read_bytes()- )+ with replacing(directory(plan, role) / f"{arm['key']}.failures.jsonl") as copy:+ shutil.copyfile(target, copy)else:expected_runtime = plan.config["runtime"].get("training")if expected_runtime and receipt.get("runtime_fingerprint") != expected_runtime:@@ -625,7 +623,10 @@ def collect(plan, stage, receipt):"input_sha256") != prepared.get("input_sha256"):raise InputValidationError("Prepared and predicted native identities differ")- with (directory(plan, role) / f"{participant['key']}.jsonl").open("w") as output:+ with (+ replacing(directory(plan, role) / f"{participant['key']}.jsonl") as written,+ written.open("w") as output,+ ):for prediction in records(target):output.write(json.dumps(@@ -653,14 +654,15 @@ def comparison(plan, role, arm, calibrated_output):path = source / f"{key}.jsonl"if calibrated_output:adjusted = source / f"{key}-calibrated.jsonl"- with adjusted.open("w") as output:+ with replacing(adjusted) as written, written.open("w") as output:for prediction in records(path):output.write(json.dumps(calibrated(prediction, plan.calibration["arms"][key])) + "\n")failures = path.with_suffix(".failures.jsonl")if failures.exists():- adjusted.with_suffix(".failures.jsonl").write_bytes(failures.read_bytes())+ with replacing(adjusted.with_suffix(".failures.jsonl")) as copy:+ shutil.copyfile(failures, copy)path = adjustedprediction_paths[key] = pathif (destination / "summary.json").exists():@@ -863,7 +865,8 @@ def score(plan):"Calibration results in results.json are in-sample; fitted temperatures were frozen before final scoring.","",]- (directory(plan, "report") / "results.md").write_text("\n".join(report_lines))+ with replacing(directory(plan, "report") / "results.md") as written:+ written.write_text("\n".join(report_lines))summary = _report_metrics(result)summary.pop("calls", None)summary["report"] = {@@ -1053,7 +1056,8 @@ def collect_reused(plan, role, participant):if checksum is not None:if digest_file(previous) != checksum:raise InputValidationError("Saved prediction evidence changed")- shutil.copyfile(previous, destination)+ with replacing(destination) as copy:+ shutil.copyfile(previous, copy)return {**pinned["receipt"],"reused_from": str(source.pk),diff --git a/tests/test_connector_poll.py b/tests/test_connector_poll.pyindex fb39594c..ce7358d1 100644--- a/tests/test_connector_poll.py+++ b/tests/test_connector_poll.py@@ -8,8 +8,9 @@ import pytestimport time_machinefrom django.db import connectionfrom django.test.utils import CaptureQueriesContext+from django.urls import reversefrom django.utils import timezone-from factories import make_connector, make_project, sync_until_live+from factories import make_connector, make_project, member_client, sync_until_livefrom fakes.vendors import LangfuseAPI, Stepfrom overbae.api.serializers import ConnectorCredentialSerializer@@ -19,7 +20,9 @@ from overbae.services.connectors.progress import checkpoint_progress, sync_progrfrom overbae.services.connectors.sync import (boundary_import_key,enqueue_connector_sync,+ prepare_connector_sync,reset_connector_import,+ will_recarve,)from overbae.services.datasets import heartbeatfrom overbae.services.mcp.resources import connector_resource_payload@@ -282,6 +285,51 @@ def test_a_sync_request_restarts_the_backfill_when_the_boundaries_changed(credenassert credential.sync_cursor == {}+def test_saving_settings_in_the_console_keeps_imported_traces(credential, langfuse):+ _traces(langfuse, 2)+ sync_until_live(credential)++ response = member_client(credential.project).post(+ reverse("connectorcredential-config", args=[credential.id]),+ {"lookback_days": 7},+ format="json",+ )++ assert response.status_code == 201+ credential.refresh_from_db()+ assert _spans(credential) == 2+ assert credential.sync_cursor == {}+++def test_switching_the_source_project_replaces_its_imported_traces(credential, langfuse):+ _traces(langfuse, 2)+ sync_until_live(credential)+ langfuse.traces.clear()+ _traces(langfuse, 1, first=10)++ member_client(credential.project).post(+ reverse("connectorcredential-config", args=[credential.id]),+ {"source_project_id": "another-project"},+ format="json",+ )+ sync_until_live(credential)++ assert _spans(credential) == 1+++def test_a_source_change_saved_during_a_recarve_still_recarves(credential, langfuse):+ _traces(langfuse, 1)+ sync_until_live(credential)+ save_sync_config(credential, source_project_id="second")+ credential.refresh_from_db()+ save_sync_config(credential, source_project_id="third")++ prepare_connector_sync(credential)++ credential.refresh_from_db()+ assert will_recarve(credential)++def test_split_trace_pages_and_retries_do_not_inflate_import_counts(credential, langfuse):start = datetime(2026, 1, 1, tzinfo=UTC)root = Step("root", "span", None, start=start, end=start + timedelta(seconds=2))diff --git a/tests/test_native_evaluation_plan.py b/tests/test_native_evaluation_plan.pyindex 77bcf9ce..ffa86654 100644--- a/tests/test_native_evaluation_plan.py+++ b/tests/test_native_evaluation_plan.py@@ -1,3 +1,4 @@+import hashlibimport jsonimport mathfrom contextlib import closing@@ -463,6 +464,32 @@ def test_overlapping_reconciliation_observes_provider_call_once(tmp_path, settinassert plan.calls["calibration_prepare"]["state"] == "completed"+def test_an_older_collection_never_tears_the_file_a_newer_attempt_published(+ tmp_path, settings, fake_modal, monkeypatch+):+ settings.MEDIA_ROOT = tmp_path+ plan = setup_plan()+ payload = b"".join(json.dumps({"key": str(i)}).encode() + b"\n" for i in range(64))+ receipt = {"failures_sha256": hashlib.sha256(payload).hexdigest()}+ newer = []++ def read_file(volume, path):+ yield payload[:100]+ if not newer:+ newer.append(path)+ native_evaluation.collect(plan, "calibration_prepare", receipt)+ yield payload[100:]++ monkeypatch.setattr(native_evaluation.modal.Volume, "_read_file", read_file)+ native_evaluation.collect(plan, "calibration_prepare", receipt)++ stage = native_evaluation.directory(plan, "calibration")+ published = [stage / "prepare-failures.jsonl", *stage.glob("*.failures.jsonl")]+ assert newer and len(published) > 1+ assert all(path.read_bytes() == payload for path in published)+ assert not list(stage.glob(".*.tmp"))++def test_pending_provider_observation_can_be_polled_again(tmp_path, settings):settings.MEDIA_ROOT = tmp_pathplan = setup_plan()