"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(strategy_store): break created_at ties so history is really newest first
ethanstoner19a1608eddb4
diff --git a/agent/src/strategy_store/sqlite_store.py b/agent/src/strategy_store/sqlite_store.pyindex a71184d17..35ed2d8c1 100644--- a/agent/src/strategy_store/sqlite_store.py+++ b/agent/src/strategy_store/sqlite_store.py@@ -475,7 +475,7 @@ class SqliteStrategyStore:where = "WHERE " + " AND ".join(clauses)rows = self._conn.execute(- f"SELECT * FROM artifacts {where} ORDER BY created_at DESC LIMIT ?",+ f"SELECT * FROM artifacts {where} ORDER BY created_at DESC, rowid DESC LIMIT ?",[*params, limit],).fetchall()return [self._row_to_artifact(row) for row in rows]@@ -645,7 +645,7 @@ class SqliteStrategyStore:"""SELECT * FROM bench_historyWHERE artifact_id = ?- ORDER BY created_at DESC+ ORDER BY created_at DESC, id DESCLIMIT ?""",(artifact_id, limit),@@ -693,7 +693,7 @@ class SqliteStrategyStore:"""SELECT * FROM decay_snapshotsWHERE artifact_id = ?- ORDER BY created_at DESC+ ORDER BY created_at DESC, id DESCLIMIT ?""",(artifact_id, limit),diff --git a/agent/src/strategy_store/store.py b/agent/src/strategy_store/store.pyindex 17bc2b10f..08df49d2e 100644--- a/agent/src/strategy_store/store.py+++ b/agent/src/strategy_store/store.py@@ -202,19 +202,23 @@ class InMemoryStrategyStore:limit: int = 100,) -> Sequence[Artifact]:"""List artifacts with composable filters, newest first."""- results: list[Artifact] = []- for art in self._artifacts.values():+ results: list[tuple[int, Artifact]] = []+ for position, art in enumerate(self._artifacts.values()):if type is not None and art.type != type:continueif status is not None and art.status != status:continueif universe is not None and art.universe != universe:continue- results.append(art)+ results.append((position, art))- # Sort by created_at descending (newest first).- results.sort(key=lambda a: a.created_at or "", reverse=True)- return results[:limit]+ # Sort by created_at descending (newest first), breaking ties on+ # insertion order. Sorting is stable and reverse=True does not reorder+ # equal keys, so without the tiebreaker records sharing a timestamp+ # come back oldest first. Timestamps collide readily: _now_iso() has+ # only the clock's resolution behind it.+ results.sort(key=lambda pair: (pair[1].created_at or "", pair[0]), reverse=True)+ return [art for _, art in results[:limit]]@_synchronizeddef update_status(@@ -299,7 +303,8 @@ class InMemoryStrategyStore:) -> Sequence[BenchResult]:"""Return bench results for an artifact, newest first."""matched = [r for r in self._bench_results if r.artifact_id == artifact_id]- matched.sort(key=lambda r: r.created_at or "", reverse=True)+ # id ascends with insertion, so it breaks timestamp ties newest first.+ matched.sort(key=lambda r: (r.created_at or "", r.id or 0), reverse=True)return matched[:limit]# -- Decay snapshots -----------------------------------------------------@@ -327,5 +332,6 @@ class InMemoryStrategyStore:) -> Sequence[DecaySnapshot]:"""Return decay snapshots for an artifact, newest first."""matched = [s for s in self._decay_snapshots if s.artifact_id == artifact_id]- matched.sort(key=lambda s: s.created_at or "", reverse=True)+ # id ascends with insertion, so it breaks timestamp ties newest first.+ matched.sort(key=lambda s: (s.created_at or "", s.id or 0), reverse=True)return matched[:limit]diff --git a/agent/tests/test_strategy_store.py b/agent/tests/test_strategy_store.pyindex 83c104949..4e49b0484 100644--- a/agent/tests/test_strategy_store.py+++ b/agent/tests/test_strategy_store.py@@ -1395,3 +1395,51 @@ class TestSchemaMigration:fetched = store2.get_artifact(aid)assert fetched is not Noneassert fetched.name == "reopen_factor"+++class TestOrderingWithTiedTimestamps:+ """Ordering must hold when created_at collides.++ _now_iso() carries only the clock's resolution, so a batch registered+ inside one tick shares a timestamp. On Linux that is rare enough to pass by+ luck; on Windows the ~15.6ms granularity makes it the normal case. Pinning+ the timestamp reproduces it on every platform.+ """++ PINNED = "2026-03-02T10:00:00+00:00"++ def _pin(self, monkeypatch, module):+ monkeypatch.setattr(module, "_now_iso", lambda: self.PINNED)++ def test_in_memory_artifacts_newest_first_on_tie(self, monkeypatch):+ from src.strategy_store import store as store_module++ self._pin(monkeypatch, store_module)+ s = store_module.InMemoryStrategyStore()+ for i in range(3):+ s.register_artifact(_make_artifact(name=f"tied_{i}"))++ names = [a.name for a in s.list_artifacts()]+ assert {a.created_at for a in s.list_artifacts()} == {self.PINNED}+ assert names == ["tied_2", "tied_1", "tied_0"]++ def test_in_memory_bench_history_newest_first_on_tie(self, monkeypatch):+ from src.strategy_store import store as store_module++ self._pin(monkeypatch, store_module)+ s = store_module.InMemoryStrategyStore()+ aid = s.register_artifact(_make_artifact(name="tied_bench"))+ for i in range(3):+ s.record_bench(BenchResult(artifact_id=aid, sharpe=float(i)))++ assert [r.sharpe for r in s.get_bench_history(aid)] == [2.0, 1.0, 0.0]++ def test_sqlite_artifacts_newest_first_on_tie(self, monkeypatch, tmp_path):+ from src.strategy_store import sqlite_store as sqlite_module++ self._pin(monkeypatch, sqlite_module)+ s = sqlite_module.SqliteStrategyStore(db_path=tmp_path / "tied.db")+ for i in range(3):+ s.register_artifact(_make_artifact(name=f"tied_{i}"))++ assert [a.name for a in s.list_artifacts()] == ["tied_2", "tied_1", "tied_0"]