amfs-http-server 0.3.62__tar.gz → 0.3.63__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.62
3
+ Version: 0.3.63
4
4
  Summary: AMFS HTTP/REST API server with SSE support
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.62"
3
+ version = "0.3.63"
4
4
  description = "AMFS HTTP/REST API server with SSE support"
5
5
  requires-python = ">=3.11"
6
6
  license = "Apache-2.0"
@@ -8711,29 +8711,132 @@ def graph_backfill(
8711
8711
  # ──────────────────────────────────────────────────────────────────────
8712
8712
 
8713
8713
 
8714
- def _compute_tiers(entries: list) -> tuple[dict[str, int], dict[str, float]]:
8715
- """Score entries and assign HMO tiers (Hot/Warm/Archive)."""
8716
- from amfs_core.tiering import PriorityScorer, TierAssigner
8714
+ def _tier_bands() -> tuple[int, int]:
8715
+ """``(hot_capacity, warm_capacity)``: the tiers are rank bands over the
8716
+ priority order — the top ``hot`` entries are Hot, the next ``warm`` Warm,
8717
+ the rest Archive (``amfs_core.tiering.TierAssigner``)."""
8718
+ from amfs_core.models import TierConfig
8719
+
8720
+ cfg = TierConfig()
8721
+ return int(cfg.hot_capacity), int(cfg.warm_capacity)
8722
+
8723
+
8724
+ def _tier_split(total: int) -> tuple[int, int, int]:
8725
+ """How many of *total* ranked entries fall in each band."""
8726
+ hot_cap, warm_cap = _tier_bands()
8727
+ hot = min(hot_cap, total)
8728
+ warm = min(warm_cap, max(0, total - hot_cap))
8729
+ return hot, warm, max(0, total - hot_cap - warm_cap)
8717
8730
 
8718
- scorer = PriorityScorer()
8719
- assigner = TierAssigner()
8720
- return assigner.assign_with_scores(entries, scorer)
8721
8731
 
8732
+ def _tier_window(tier: int, limit: int) -> tuple[int, int]:
8733
+ """``(offset, limit)`` into the priority ranking for one tier's page."""
8734
+ hot_cap, warm_cap = _tier_bands()
8735
+ if tier == 1:
8736
+ return 0, min(limit, hot_cap)
8737
+ if tier == 2:
8738
+ return hot_cap, min(limit, warm_cap)
8739
+ return hot_cap + warm_cap, limit
8722
8740
 
8723
- def _tiered_entries(
8724
- mem: AgentMemory, vis: Any | None, agent_id: str | None
8725
- ) -> tuple[list[MemoryEntry], tuple[dict[str, int], dict[str, float]]]:
8726
- """The entries a tiers page scores, and their tiers and scores.
8727
8741
 
8728
- The tiering is a Python scorer over the whole visible set, so the set has
8729
- to be loaded; this loads only the named agent's rows when there is one
8730
- and runs the load, the visibility pass and the scoring together off the
8731
- event loop. Synchronous: call it via ``_offload``.
8742
+ #: Entries per round trip when the tiers have to be scored in Python.
8743
+ _TIER_SCAN_PAGE = 2000
8744
+
8745
+
8746
+ def _tier_scan(
8747
+ mem: AgentMemory,
8748
+ agent_id: str | None,
8749
+ *,
8750
+ scope: Any | None,
8751
+ py_filter: Any | None,
8752
+ vis: Any | None,
8753
+ keep: int,
8754
+ ) -> tuple[int, float, list[tuple[float, MemoryEntry]]]:
8755
+ """Score the visible entries a page at a time, keeping only the top *keep*.
8756
+
8757
+ The fallback for a visibility rule that only exists in Python or an
8758
+ adapter that cannot order by the score. Bounded in memory: a page is
8759
+ scored, folded into the count and the running sum, and all but the top
8760
+ *keep* are dropped before the next page is read.
8761
+
8762
+ The caller's visibility is ``(scope, py_filter)`` as ``_visibility_scope``
8763
+ gave it: *scope* narrows each page in SQL, *py_filter* runs over the
8764
+ loaded rows. An adapter that cannot take a scope or page (the in-memory
8765
+ ones) gets one unpaged ``list()``, and then *vis* — the filter object the
8766
+ scope was derived from — runs over it, so a rule that exists only as a
8767
+ predicate is still applied rather than dropped. Returns
8768
+ ``(count, score_sum, top)`` with *top* highest first. Synchronous: call
8769
+ it via ``_offload``.
8732
8770
  """
8733
- entries = _entries_by_agent(mem, agent_id) if agent_id else mem.list()
8734
- if vis is not None:
8735
- entries = vis.filter_entries(entries)
8736
- return entries, _compute_tiers(entries)
8771
+ import heapq
8772
+
8773
+ from amfs_core.tiering import PriorityScorer
8774
+
8775
+ scorer = PriorityScorer()
8776
+ now = datetime.now(UTC)
8777
+ count = 0
8778
+ score_sum = 0.0
8779
+ # A min-heap of (score, tiebreak, entry); the smallest is evicted first.
8780
+ top: list[tuple[float, int, MemoryEntry]] = []
8781
+ seq = 0
8782
+
8783
+ def fold(entries: list[MemoryEntry], rule: Any | None) -> None:
8784
+ nonlocal count, score_sum, seq
8785
+ if rule is not None:
8786
+ entries = rule.filter_entries(entries)
8787
+ for e in entries:
8788
+ if agent_id and e.provenance.agent_id != agent_id:
8789
+ continue
8790
+ s = scorer.score(e, now=now)
8791
+ count += 1
8792
+ score_sum += s
8793
+ seq -= 1 # earlier rows win ties, as the stable sort did
8794
+ item = (s, seq, e)
8795
+ if len(top) < keep:
8796
+ heapq.heappush(top, item)
8797
+ elif item > top[0]:
8798
+ heapq.heapreplace(top, item)
8799
+
8800
+ offset = 0
8801
+ adapter = mem._adapter
8802
+ while True:
8803
+ try:
8804
+ page = adapter.list(
8805
+ agent_id=agent_id, scope=scope, limit=_TIER_SCAN_PAGE, offset=offset
8806
+ )
8807
+ except TypeError:
8808
+ # No scope or paging in this adapter: the whole account, and the
8809
+ # visibility rule — whichever form it took — applied here.
8810
+ rule = py_filter if py_filter is not None else (vis if scope is not None else None)
8811
+ fold(_entries_by_agent(mem, agent_id) if agent_id else mem.list(), rule)
8812
+ break
8813
+ fold(page, py_filter)
8814
+ if len(page) < _TIER_SCAN_PAGE:
8815
+ break
8816
+ offset += _TIER_SCAN_PAGE
8817
+ ranked = sorted(top, reverse=True)
8818
+ return count, score_sum, [(s, e) for s, _, e in ranked]
8819
+
8820
+
8821
+ def _tiers_in_sql(adapter: Any, py_filter: Any | None) -> bool:
8822
+ """Whether the tiers can be read as one ranked page from the database:
8823
+ the adapter orders by the score and no Python-only visibility rule hides
8824
+ an unknown share of the rows."""
8825
+ return py_filter is None and callable(getattr(adapter, "list_by_priority", None))
8826
+
8827
+
8828
+ def _tier_entry_dict(e: MemoryEntry, tier: int, score: float) -> dict[str, Any]:
8829
+ return {
8830
+ "entity_path": e.entity_path,
8831
+ "key": e.key,
8832
+ "confidence": e.confidence,
8833
+ "tier": tier,
8834
+ "priority_score": round(score, 6),
8835
+ "recall_count": getattr(e, "recall_count", 0),
8836
+ "importance_score": getattr(e, "importance_score", None),
8837
+ "written_at": e.provenance.written_at.isoformat(),
8838
+ "agent_id": e.provenance.agent_id,
8839
+ }
8737
8840
 
8738
8841
 
8739
8842
  @app.get("/api/v1/pro/tiers/distribution")
@@ -8742,32 +8845,36 @@ async def tiers_distribution(
8742
8845
  agent_id: str | None = Query(None),
8743
8846
  _auth: str | None = Depends(verify_api_key),
8744
8847
  ) -> dict[str, Any]:
8745
- """Return HMO tier distribution (Hot / Warm / Archive)."""
8746
- entries, (tiers, scores) = await _offload(
8747
- _db_executor, _tiered_entries, _get_memory(), _active_visibility_filter(request), agent_id
8748
- )
8749
-
8750
- hot = warm = archive = scored_count = 0
8751
- score_sum = 0.0
8752
- for key, tier in tiers.items():
8753
- if tier == 1:
8754
- hot += 1
8755
- elif tier == 2:
8756
- warm += 1
8757
- else:
8758
- archive += 1
8759
- s = scores.get(key)
8760
- if s is not None:
8761
- scored_count += 1
8762
- score_sum += s
8848
+ """Return HMO tier distribution (Hot / Warm / Archive).
8849
+
8850
+ The tiers are rank bands over the priority score, so the distribution is
8851
+ a count and a mean: the database computes both (``priority_stats``) and
8852
+ no entry is loaded. The previous version listed the whole account and
8853
+ scored it in Python; on a 420K-entry account the two requests the tiers
8854
+ page makes together exhausted an 8 GiB instance and took every other
8855
+ request on it down with them.
8856
+ """
8857
+ mem = _get_memory()
8858
+ scope, py_filter = _visibility_scope(request)
8859
+ if _tiers_in_sql(mem._adapter, py_filter):
8860
+ total, mean = await _offload(
8861
+ _db_executor, mem._adapter.priority_stats, scope=scope, agent_id=agent_id
8862
+ )
8863
+ else:
8864
+ total, score_sum, _top = await _offload(
8865
+ _db_executor, _tier_scan, mem, agent_id,
8866
+ scope=scope, py_filter=py_filter, vis=_active_visibility_filter(request), keep=1,
8867
+ )
8868
+ mean = score_sum / total if total else None
8763
8869
 
8870
+ hot, warm, archive = _tier_split(total)
8764
8871
  return {
8765
- "total": len(entries),
8872
+ "total": total,
8766
8873
  "hot": hot,
8767
8874
  "warm": warm,
8768
8875
  "archive": archive,
8769
- "scored": scored_count,
8770
- "avg_priority_score": round(score_sum / scored_count, 6) if scored_count else None,
8876
+ "scored": total,
8877
+ "avg_priority_score": round(mean, 6) if mean is not None else None,
8771
8878
  }
8772
8879
 
8773
8880
 
@@ -8779,28 +8886,28 @@ async def tiers_entries(
8779
8886
  agent_id: str | None = Query(None),
8780
8887
  _auth: str | None = Depends(verify_api_key),
8781
8888
  ) -> list[dict[str, Any]]:
8782
- """Return entries for a given HMO tier as a flat array."""
8783
- entries, (tier_map, score_map) = await _offload(
8784
- _db_executor, _tiered_entries, _get_memory(), _active_visibility_filter(request), agent_id
8785
- )
8786
-
8787
- filtered = [e for e in entries if tier_map.get(e.entry_key) == tier]
8788
- filtered.sort(key=lambda e: score_map.get(e.entry_key, 0.0), reverse=True)
8889
+ """Return entries for a given HMO tier as a flat array, highest priority
8890
+ first. One page of the ranking, read at the tier's offset."""
8891
+ mem = _get_memory()
8892
+ scope, py_filter = _visibility_scope(request)
8893
+ offset, page = _tier_window(tier, limit)
8894
+ if _tiers_in_sql(mem._adapter, py_filter):
8895
+ from amfs_core.tiering import PriorityScorer
8896
+
8897
+ now = datetime.now(UTC)
8898
+ entries = await _offload(
8899
+ _db_executor, mem._adapter.list_by_priority,
8900
+ scope=scope, agent_id=agent_id, limit=page, offset=offset, now=now,
8901
+ )
8902
+ scorer = PriorityScorer()
8903
+ return [_tier_entry_dict(e, tier, scorer.score(e, now=now)) for e in entries]
8789
8904
 
8790
- return [
8791
- {
8792
- "entity_path": e.entity_path,
8793
- "key": e.key,
8794
- "confidence": e.confidence,
8795
- "tier": tier,
8796
- "priority_score": round(score_map.get(e.entry_key, 0.0), 6),
8797
- "recall_count": getattr(e, "recall_count", 0),
8798
- "importance_score": getattr(e, "importance_score", None),
8799
- "written_at": e.provenance.written_at.isoformat(),
8800
- "agent_id": e.provenance.agent_id,
8801
- }
8802
- for e in filtered[:limit]
8803
- ]
8905
+ _count, _sum, top = await _offload(
8906
+ _db_executor, _tier_scan, mem, agent_id,
8907
+ scope=scope, py_filter=py_filter, vis=_active_visibility_filter(request),
8908
+ keep=offset + page,
8909
+ )
8910
+ return [_tier_entry_dict(e, tier, s) for s, e in top[offset:offset + page]]
8804
8911
 
8805
8912
 
8806
8913
  # ──────────────────────────────────────────────────────────────────────