Skip to content
Merged
46 changes: 37 additions & 9 deletions autobot-backend/api/_connector_sync_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,48 @@
The sync holds a config loaded before it began, with its decrypted credentials merged in. Saving
that back would store the credentials in Redis, undo an edit made during the sync, and bring back
a connector deleted during it. So only this field is written, in one transaction on the key.

It only moves forward (#20758): two runs can still overlap once a lease is lost, and the one that
finishes first must not set an older time over a newer one, which would widen the next ``since``.
"""

import asyncio
import json
from datetime import datetime, timezone
from typing import Literal

from redis.exceptions import WatchError

from autobot_shared.logging_manager import get_logger
from autobot_shared.redis_client import get_redis_client
from autobot_shared.time_utils import now_utc
from autobot_shared.time_utils import now_utc, parse_utc_iso

logger = get_logger(__name__)

_MAX_ATTEMPTS = 5


def _write_last_sync(redis, key: str, when: str) -> bool | None:
"""True when written, False when the connector is gone, None when it exists but kept changing."""
def _aware(value) -> datetime | None:
"""A comparable UTC time from a datetime or an ISO string; None when absent or unreadable."""
if isinstance(value, str):
try:
return parse_utc_iso(value)
except ValueError:
logger.warning("Ignoring an unreadable stored last_sync_at %r", value)
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
return None


def _is_later(when: datetime, current) -> bool:
current = _aware(current)
return current is None or when > current


def _write_last_sync(redis, key: str, when: datetime) -> datetime | Literal[False] | None:
"""The time Redis holds afterwards: *when*, or a later (or equal) one already stored. False when
the connector is gone, None when it exists but kept changing."""
with redis.pipeline() as pipe:
for _ in range(_MAX_ATTEMPTS):
try:
Expand All @@ -34,11 +58,15 @@ def _write_last_sync(redis, key: str, when: str) -> bool | None:
pipe.unwatch()
return False
record = json.loads(raw)
record["last_sync_at"] = when
current = _aware(record.get("last_sync_at"))
if current is not None and current >= when:
pipe.unwatch()
return current
record["last_sync_at"] = when.isoformat()
pipe.multi()
pipe.set(key, json.dumps(record, ensure_ascii=False))
pipe.execute()
return True
return when
except WatchError:
continue
logger.warning("Could not record the last sync on %s: it kept changing", key)
Expand All @@ -56,8 +84,8 @@ async def record_last_sync(instance, key: str, sync_result) -> bool:
redis = get_redis_client(database="knowledge")
if getattr(sync_result, "status", None) != "success":
return bool(await asyncio.to_thread(redis.exists, key))
when = sync_result.completed_at or now_utc()
stored = await asyncio.to_thread(_write_last_sync, redis, key, when.isoformat())
if stored is True:
instance.config.last_sync_at = when # what the status route reads; only once Redis has it
when = _aware(sync_result.completed_at) or now_utc()
stored = await asyncio.to_thread(_write_last_sync, redis, key, when)
if isinstance(stored, datetime) and _is_later(stored, instance.config.last_sync_at):
instance.config.last_sync_at = stored # what the status route reads: what Redis holds
return stored is not False
82 changes: 76 additions & 6 deletions autobot-backend/api/connector_sync_result_19714_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,25 +43,29 @@ def execute() -> None:

def test_only_the_time_changes_on_the_current_record() -> None:
store = {"k": json.dumps({"name": "edited during the sync", "config": {"host": "h"}})}
assert result._write_last_sync(_redis(store), "k", "T") is True
assert json.loads(store["k"]) == {"name": "edited during the sync", "config": {"host": "h"}, "last_sync_at": "T"}
assert result._write_last_sync(_redis(store), "k", _WHEN) == _WHEN
assert json.loads(store["k"]) == {
"name": "edited during the sync",
"config": {"host": "h"},
"last_sync_at": _WHEN.isoformat(),
}


def test_a_connector_deleted_during_the_sync_stays_deleted() -> None:
store: dict = {}
assert result._write_last_sync(_redis(store), "k", "T") is False
assert result._write_last_sync(_redis(store), "k", _WHEN) is False
assert store == {}


def test_an_edit_racing_the_write_is_retried_on_the_new_record() -> None:
store = {"k": json.dumps({"name": "n"})}
assert result._write_last_sync(_redis(store, conflicts=1), "k", "T") is True
assert json.loads(store["k"])["last_sync_at"] == "T"
assert result._write_last_sync(_redis(store, conflicts=1), "k", _WHEN) == _WHEN
assert json.loads(store["k"])["last_sync_at"] == _WHEN.isoformat()


def test_it_gives_up_rather_than_spinning() -> None:
store = {"k": json.dumps({"name": "n"})}
assert result._write_last_sync(_redis(store, conflicts=99), "k", "T") is None, "exists, but nothing was written"
assert result._write_last_sync(_redis(store, conflicts=99), "k", _WHEN) is None, "exists, but nothing was written"
assert "last_sync_at" not in json.loads(store["k"])


Expand Down Expand Up @@ -147,3 +151,69 @@ async def test_a_stopped_run_of_a_deleted_connector_still_reads_as_deleted() ->
run = SimpleNamespace(completed_at=_WHEN, status="failed")
with patch.object(result, "get_redis_client", return_value=_redis({})):
assert await result.record_last_sync(SimpleNamespace(config=SimpleNamespace()), "k", run) is False


# #20758: two overlapping runs can finish out of order; the stored and live times only move forward.
_EARLIER = datetime(2026, 11, 1, 12, 0) # naive, as some connectors report it: read as UTC


def test_an_earlier_finishing_run_keeps_the_later_stored_time() -> None:
store = {"k": json.dumps({"name": "n", "last_sync_at": _WHEN.isoformat()})}
assert result._write_last_sync(_redis(store), "k", result._aware(_EARLIER)) == _WHEN, "it reports the time kept"
assert json.loads(store["k"])["last_sync_at"] == _WHEN.isoformat()


def test_a_later_run_still_moves_the_stored_time_forward() -> None:
"""The control: an older stored time (written by an older format, with a Z) is replaced."""
store = {"k": json.dumps({"name": "n", "last_sync_at": "2026-11-01T12:00:00Z"})}
assert result._write_last_sync(_redis(store), "k", _WHEN) == _WHEN
assert json.loads(store["k"])["last_sync_at"] == _WHEN.isoformat()


def test_an_unreadable_stored_time_is_replaced() -> None:
store = {"k": json.dumps({"name": "n", "last_sync_at": "not a time"})}
assert result._write_last_sync(_redis(store), "k", _WHEN) == _WHEN
assert json.loads(store["k"])["last_sync_at"] == _WHEN.isoformat()


@pytest.mark.asyncio
async def test_out_of_order_completion_leaves_the_later_time_everywhere() -> None:
"""The newer run finishes first, then the older one: both the stored and the live time stay at
the newer run's."""
store = {"k": json.dumps({"name": "n"})}
instance = SimpleNamespace(config=SimpleNamespace(last_sync_at=None))
with patch.object(result, "get_redis_client", return_value=_redis(store)):
for completed_at in (_WHEN, _EARLIER):
run = SimpleNamespace(completed_at=completed_at, status="success")
assert await result.record_last_sync(instance, "k", run) is True
assert json.loads(store["k"])["last_sync_at"] == _WHEN.isoformat()
assert instance.config.last_sync_at == _WHEN


@pytest.mark.asyncio
async def test_a_run_behind_the_stored_time_leaves_the_live_value_at_the_stored_one() -> None:
"""Review of #20801: the stored record and the live instance are separate. A later time already
in Redis (from another worker's run) wins over this run's older one on the live value too, so
the status route and Redis agree."""
store = {"k": json.dumps({"name": "n", "last_sync_at": _WHEN.isoformat()})}
instance = SimpleNamespace(config=SimpleNamespace(last_sync_at=None))
run = SimpleNamespace(completed_at=_EARLIER, status="success")
with patch.object(result, "get_redis_client", return_value=_redis(store)):
assert await result.record_last_sync(instance, "k", run) is True
assert json.loads(store["k"])["last_sync_at"] == _WHEN.isoformat()
assert instance.config.last_sync_at == _WHEN, "the live value disagrees with Redis"


@pytest.mark.asyncio
async def test_an_equal_stored_time_is_kept_and_reported() -> None:
"""A tie is not later: Redis is left as it is, and the live value takes that same time."""
stored = {"name": "n", "last_sync_at": _WHEN.isoformat(), "note": "untouched"}
store = {"k": json.dumps(stored)}
redis = _redis(store)
instance = SimpleNamespace(config=SimpleNamespace(last_sync_at=None))
with patch.object(result, "get_redis_client", return_value=redis):
run = SimpleNamespace(completed_at=_WHEN, status="success")
assert await result.record_last_sync(instance, "k", run) is True
redis.pipeline.return_value.set.assert_not_called()
assert json.loads(store["k"]) == stored, "a tie rewrote the record"
assert instance.config.last_sync_at == _WHEN