amfs-http-server 0.3.61__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,10 +1,10 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.61
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
7
- Requires-Dist: amfs-core>=0.3.52
7
+ Requires-Dist: amfs-core>=0.3.53
8
8
  Requires-Dist: amfs>=0.5.40
9
9
  Requires-Dist: fastapi>=0.115
10
10
  Requires-Dist: httpx>=0.27
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.61"
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"
@@ -27,7 +27,7 @@ dependencies = [
27
27
  # unexpected keyword, _scope_block swallows it, and the block disappears —
28
28
  # while an adapter that ignored the argument instead would name another
29
29
  # agent's private keys. Either way the floor is what makes the rule real.
30
- "amfs-core>=0.3.52",
30
+ "amfs-core>=0.3.53",
31
31
  "fastapi>=0.115",
32
32
  # 0.37 is where uvicorn.run() grew timeout_worker_healthcheck, which
33
33
  # main() passes unconditionally; on anything older that is a TypeError
@@ -2576,43 +2576,126 @@ async def list_entries(
2576
2576
  return {"entries": payload, "total": total}
2577
2577
 
2578
2578
 
2579
+ #: The most entity summaries one page may ask for.
2580
+ _ENTITY_SUMMARIES_PAGE_MAX = 500
2581
+ _ENTITY_SUMMARY_SORTS = (
2582
+ "last_updated",
2583
+ "entry_count",
2584
+ "total_recalls",
2585
+ "avg_confidence",
2586
+ "avg_confidence_asc",
2587
+ "entity_path",
2588
+ )
2589
+
2590
+
2579
2591
  @app.get("/api/v1/entities")
2580
2592
  async def list_entity_summaries(
2581
2593
  request: Request,
2594
+ q: str | None = Query(None, max_length=500),
2595
+ agent: str | None = Query(None, max_length=200),
2596
+ min_confidence: float | None = Query(None, ge=0.0, le=1.0),
2597
+ sort: str = Query("last_updated"),
2598
+ limit: int | None = Query(None, ge=1, le=_ENTITY_SUMMARIES_PAGE_MAX),
2599
+ offset: int = Query(0, ge=0),
2582
2600
  _auth: str | None = Depends(verify_api_key),
2583
2601
  ) -> dict[str, Any]:
2584
2602
  """Per-entity aggregates without entry values — a few KB instead of the
2585
- multi-MB /entries payload. Dashboards should prefer this endpoint."""
2603
+ multi-MB /entries payload. Dashboards should prefer this endpoint.
2604
+
2605
+ With ``limit`` the response is one page of paths containing ``q`` that
2606
+ ``agent`` has written to and whose mean confidence reaches
2607
+ ``min_confidence``, ordered by ``sort`` (``last_updated``,
2608
+ ``entry_count``, ``total_recalls``, ``avg_confidence``,
2609
+ ``avg_confidence_asc``, ``entity_path``), and carries ``total``, the
2610
+ count before paging. Filtering and paging happen in SQL alongside the
2611
+ visibility predicate; an adapter without those parameters, or a
2612
+ visibility rule that has to run over loaded entries, is filtered and
2613
+ paged here after the fact.
2614
+ """
2586
2615
  mem = _get_memory()
2587
2616
  adapter = mem._adapter
2617
+ if sort not in _ENTITY_SUMMARY_SORTS:
2618
+ raise HTTPException(status_code=400, detail=f"unknown sort {sort!r}")
2588
2619
 
2589
2620
  scope, py_vis = _visibility_scope(request)
2621
+ narrowed = (
2622
+ bool(q) or bool(agent) or min_confidence is not None
2623
+ or limit is not None or sort != "last_updated"
2624
+ )
2590
2625
 
2591
- def _summaries() -> list[dict[str, Any]]:
2626
+ def _page_here(rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int | None]:
2627
+ """Filter, order and page rows that came back whole."""
2628
+ if q:
2629
+ needle = q.lower()
2630
+ rows = [r for r in rows if needle in str(r.get("entity_path", "")).lower()]
2631
+ if agent:
2632
+ rows = [r for r in rows if agent in (r.get("agents") or [])]
2633
+ if min_confidence is not None:
2634
+ rows = [r for r in rows if float(r.get("avg_confidence") or 0) >= min_confidence]
2635
+ if sort == "entity_path":
2636
+ rows.sort(key=lambda r: str(r.get("entity_path", "")))
2637
+ elif sort == "avg_confidence_asc":
2638
+ rows.sort(key=lambda r: (r.get("avg_confidence") or 0, str(r.get("entity_path", ""))))
2639
+ elif sort != "last_updated":
2640
+ rows.sort(key=lambda r: (-(r.get(sort) or 0), str(r.get("entity_path", ""))))
2641
+ if limit is None:
2642
+ return rows, None
2643
+ return rows[offset:offset + limit], len(rows)
2644
+
2645
+ def _summaries() -> tuple[list[dict[str, Any]], int | None]:
2592
2646
  """Off the event loop: one GROUP BY where the adapter and the
2593
- visibility rule allow it, a load-and-reduce otherwise."""
2647
+ visibility rule allow it, a load-and-reduce otherwise. Returns the
2648
+ rows and, when paged, the count before paging."""
2594
2649
  if py_vis is None:
2595
- try:
2596
- # The visibility rule travels into the GROUP BY as a
2597
- # predicate, so a per-user dashboard gets the same one query
2598
- # an admin does. Only passed when there is one: the ABC's
2599
- # default implementation does not take it.
2600
- if scope is None:
2601
- return adapter.entity_summaries()
2602
- return adapter.entity_summaries(scope=scope)
2603
- except TypeError:
2604
- # An adapter without SQL scoping; reduce over its rows.
2605
- pass
2650
+ # The visibility rule travels into the GROUP BY as a predicate,
2651
+ # so a per-user dashboard gets the same one query an admin does.
2652
+ # Only passed when there is one: the ABC's default implementation
2653
+ # does not take it. Searched and paged in SQL first; an adapter
2654
+ # without those parameters returns the whole list and is paged
2655
+ # here.
2656
+ kwargs: dict[str, Any] = {}
2657
+ if scope is not None:
2658
+ kwargs["scope"] = scope
2659
+ paged = {
2660
+ **kwargs,
2661
+ "q": q or None,
2662
+ "agent": agent or None,
2663
+ "min_confidence": min_confidence,
2664
+ "sort": sort,
2665
+ "limit": limit,
2666
+ "offset": offset,
2667
+ }
2668
+ for attempt in ([paged, kwargs] if narrowed else [kwargs]):
2669
+ try:
2670
+ rows = adapter.entity_summaries(**attempt)
2671
+ except TypeError:
2672
+ continue
2673
+ if attempt is not paged:
2674
+ return _page_here(rows) # the whole list, from an older adapter
2675
+ if limit is None:
2676
+ return rows, None # searched and ordered in SQL, unpaged
2677
+ total = int(rows[0].pop("total", 0)) if rows else 0
2678
+ for r in rows[1:]:
2679
+ r.pop("total", None)
2680
+ if not rows and offset:
2681
+ # A page past the end says nothing about the count; the
2682
+ # first page does.
2683
+ first = adapter.entity_summaries(**{**paged, "limit": 1, "offset": 0})
2684
+ total = int(first[0].get("total", 0)) if first else 0
2685
+ return rows, total
2606
2686
  from amfs_core.aggregates import entity_summaries_from_entries
2607
2687
 
2608
2688
  entries = mem.list()
2609
2689
  vis = py_vis if py_vis is not None else _active_visibility_filter(request)
2610
2690
  if vis is not None:
2611
2691
  entries = vis.filter_entries(entries)
2612
- return entity_summaries_from_entries(entries)
2692
+ return _page_here(entity_summaries_from_entries(entries))
2613
2693
 
2614
- summaries = await _offload(_db_executor, _summaries)
2615
- return json.loads(json.dumps({"entities": summaries}, default=str))
2694
+ summaries, total = await _offload(_db_executor, _summaries)
2695
+ out: dict[str, Any] = {"entities": summaries}
2696
+ if limit is not None:
2697
+ out.update({"total": total, "limit": limit, "offset": offset})
2698
+ return json.loads(json.dumps(out, default=str))
2616
2699
 
2617
2700
 
2618
2701
  @app.post("/api/v1/aggregate")
@@ -3940,8 +4023,18 @@ async def retrieve_entries(
3940
4023
  @app.get("/api/v1/stats")
3941
4024
  async def get_stats(
3942
4025
  request: Request,
4026
+ breakdown: bool = True,
3943
4027
  _auth: str | None = Depends(verify_api_key),
3944
4028
  ) -> dict[str, Any]:
4029
+ """Aggregate stats for the account.
4030
+
4031
+ ``breakdown=false`` leaves out the per-agent and per-entity count maps
4032
+ (``agents``, ``entities``), which on a large account are most of the
4033
+ response; ``total_agents``, ``total_entities`` and the
4034
+ ``entity_confidence`` buckets stay, on every route to this answer — the
4035
+ SQL aggregate and the loaded-and-filtered one alike. A dashboard hero
4036
+ wants the totals; the health page wants the buckets.
4037
+ """
3945
4038
  mem = _get_memory()
3946
4039
 
3947
4040
  scope, py_vis = _visibility_scope(request)
@@ -3954,15 +4047,24 @@ async def get_stats(
3954
4047
  "oldest_entry" vs "oldest_entry_at") is dropped to None. Both scoped
3955
4048
  routes below produce the same keys as the unscoped aggregate."""
3956
4049
  if py_vis is None:
3957
- try:
3958
- # The visibility rule as a predicate in the aggregate: a
3959
- # per-user dashboard gets the same query an admin does. Only
3960
- # passed when there is one; the ABC default takes no scope.
3961
- if scope is None:
3962
- return mem._adapter.stats_extended()
3963
- return mem._adapter.stats_extended(scope=scope)
3964
- except TypeError:
3965
- pass # an adapter without SQL scoping; reduce over its rows
4050
+ # The visibility rule as a predicate in the aggregate: a
4051
+ # per-user dashboard gets the same query an admin does. Only
4052
+ # passed when there is one; the ABC default takes no scope.
4053
+ kwargs: dict[str, Any] = {}
4054
+ if scope is not None:
4055
+ kwargs["scope"] = scope
4056
+ # Without the maps first; then as the adapter knows the call. An
4057
+ # adapter that takes neither keyword reduces over its rows below.
4058
+ attempts = [kwargs] if breakdown else [{**kwargs, "breakdown": False}, kwargs]
4059
+ for attempt in attempts:
4060
+ try:
4061
+ stats = mem._adapter.stats_extended(**attempt)
4062
+ except TypeError:
4063
+ continue
4064
+ if not breakdown:
4065
+ stats.pop("agents", None)
4066
+ stats.pop("entities", None)
4067
+ return stats
3966
4068
  # A filter that can only run over loaded entries: load, filter,
3967
4069
  # aggregate with the same shared helper the adapter defaults use.
3968
4070
  from amfs_core.aggregates import extended_stats_from_entries
@@ -3971,7 +4073,11 @@ async def get_stats(
3971
4073
  vis = py_vis if py_vis is not None else _active_visibility_filter(request)
3972
4074
  if vis is not None:
3973
4075
  entries = vis.filter_entries(entries)
3974
- return extended_stats_from_entries(entries)
4076
+ stats = extended_stats_from_entries(entries)
4077
+ if not breakdown:
4078
+ stats.pop("agents", None)
4079
+ stats.pop("entities", None)
4080
+ return stats
3975
4081
 
3976
4082
  stats = await _offload(_db_executor, _stats)
3977
4083
  return json.loads(json.dumps(stats, default=str))
@@ -6572,10 +6678,19 @@ def upsert_graph_edge_endpoint(
6572
6678
  # ──────────────────────────────────────────────────────────────────────
6573
6679
 
6574
6680
 
6681
+ #: The most enriched agents one page may ask for.
6682
+ _ENRICHED_AGENTS_PAGE_MAX = 500
6683
+
6684
+
6575
6685
  @app.get("/api/v1/agents/enriched")
6576
6686
  def list_agents_enriched(
6577
6687
  request: Request,
6578
6688
  histograms: bool = True,
6689
+ q: str | None = Query(None, max_length=200),
6690
+ platform: str | None = Query(None, max_length=100),
6691
+ sort: str = Query("last_active"),
6692
+ limit: int | None = Query(None, ge=1, le=_ENRICHED_AGENTS_PAGE_MAX),
6693
+ offset: int = Query(0, ge=0),
6579
6694
  _auth: str | None = Depends(verify_api_key),
6580
6695
  ) -> dict[str, Any]:
6581
6696
  """Return enriched agent info with activity histograms.
@@ -6583,15 +6698,58 @@ def list_agents_enriched(
6583
6698
  Pass histograms=false to skip the per-agent activity histogram queries —
6584
6699
  summary consumers (e.g. the dashboard overview's agent count) only need
6585
6700
  the roster, and the histograms cost up to 100 extra queries per call.
6701
+
6702
+ With ``limit`` the response is one page, searched by ``q``, kept to one
6703
+ ``platform`` and ordered by ``sort`` (``last_active``,
6704
+ ``entries_written``, ``created_at``, ``agent_id``), and carries
6705
+ ``total`` — the number of agents the caller may see that match — and
6706
+ ``active_7d``, how many of those were active in the last seven days.
6707
+ Paging and visibility both happen in SQL, so a page is a page of visible
6708
+ agents; an adapter without those parameters is filtered here, unpaged,
6709
+ as before. Without ``limit`` the whole roster is returned, 3 MB on a
6710
+ 6,000-agent account — a directory should page.
6586
6711
  """
6587
6712
  mem = _get_memory()
6588
- agents = mem._adapter.list_agents_enriched(namespace=mem.namespace)
6589
6713
  allowed = _visible_agent_ids(request)
6590
- if allowed is not None:
6591
- agents = [
6592
- a for a in agents
6593
- if (a.get("agent_id") or a.get("agentId", "")) in allowed
6594
- ]
6714
+ paged = limit is not None
6715
+ narrowing: dict[str, Any] = {
6716
+ "agent_ids": sorted(allowed) if allowed is not None else None,
6717
+ "q": q or None,
6718
+ "platform": platform or None,
6719
+ "sort": sort,
6720
+ }
6721
+ try:
6722
+ agents = mem._adapter.list_agents_enriched(
6723
+ namespace=mem.namespace, limit=limit, offset=offset, **narrowing,
6724
+ )
6725
+ except ValueError as exc:
6726
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
6727
+ except TypeError:
6728
+ # An adapter without search or paging: the visibility rule runs here
6729
+ # and the roster is whole.
6730
+ paged = False
6731
+ agents = mem._adapter.list_agents_enriched(namespace=mem.namespace)
6732
+ if allowed is not None:
6733
+ agents = [
6734
+ a for a in agents
6735
+ if (a.get("agent_id") or a.get("agentId", "")) in allowed
6736
+ ]
6737
+ total: int | None = None
6738
+ active_7d: int | None = None
6739
+ if paged:
6740
+ total = int(agents[0].pop("total", 0)) if agents else 0
6741
+ active_7d = int(agents[0].pop("active_7d", 0)) if agents else 0
6742
+ for agent in agents[1:]:
6743
+ agent.pop("total", None)
6744
+ agent.pop("active_7d", None)
6745
+ if not agents and offset:
6746
+ # A page past the end says nothing about the count; the first
6747
+ # page does.
6748
+ first = mem._adapter.list_agents_enriched(
6749
+ namespace=mem.namespace, limit=1, offset=0, **narrowing,
6750
+ )
6751
+ total = int(first[0].get("total", 0)) if first else 0
6752
+ active_7d = int(first[0].get("active_7d", 0)) if first else 0
6595
6753
  if histograms:
6596
6754
  for agent in agents[:100]:
6597
6755
  aid = agent.get("agent_id") or agent.get("agentId", "")
@@ -6599,7 +6757,12 @@ def list_agents_enriched(
6599
6757
  agent["activity_histogram"] = mem._adapter.get_agent_activity_histogram(
6600
6758
  aid, days=7, namespace=mem.namespace,
6601
6759
  )
6602
- return {"agents": agents}
6760
+ out: dict[str, Any] = {"agents": agents}
6761
+ if paged:
6762
+ out.update({
6763
+ "total": total, "active_7d": active_7d, "limit": limit, "offset": offset,
6764
+ })
6765
+ return out
6603
6766
 
6604
6767
 
6605
6768
  @app.get("/api/v1/agent-groups")
@@ -6838,17 +7001,45 @@ def dismiss_cluster_suggestion_endpoint(
6838
7001
 
6839
7002
 
6840
7003
  # The cluster compile walks every agent in the namespace and is pure Python
6841
- # CPU — minutes on an account with thousands of agents. The dashboard's Agents
6842
- # page POSTs it on every mount, so without a guard two tabs or one reload queue
6843
- # a second full compile behind the first while the process is pinned at one
6844
- # core. One compile at a time per process, and a compile that finished within
6845
- # the window is reused rather than repeated; the caller's ``ok`` is unchanged
6846
- # because it only ever waited for the suggestions to be refreshed.
7004
+ # CPU. The dashboard's Agents page POSTs it on every mount, so without a guard
7005
+ # two tabs or one reload queue a second compile behind the first. One compile
7006
+ # at a time per process, in the background; a compile that finished within the
7007
+ # window — on any instance, read from the stored digest — is reused rather
7008
+ # than repeated. The per-process timestamp is the fallback for an adapter
7009
+ # that cannot say when the digest was compiled.
6847
7010
  _CLUSTER_RECOMPUTE_MIN_INTERVAL_S = float(
6848
7011
  os.environ.get("AMFS_CLUSTER_RECOMPUTE_MIN_INTERVAL_S", "300"),
6849
7012
  )
6850
7013
  _cluster_recompute_lock = threading.Lock()
6851
7014
  _cluster_recompute_last: dict[str, float] = {}
7015
+ _cluster_recompute_inflight: set[str] = set()
7016
+
7017
+
7018
+ def _cluster_digest_compiled_at(adapter: Any, namespace: str) -> datetime | None:
7019
+ """When this account's cluster digest was last compiled, or None."""
7020
+ get = getattr(adapter, "get_digest", None)
7021
+ if not callable(get):
7022
+ return None
7023
+ try:
7024
+ from amfs_core.models import DigestType
7025
+
7026
+ digest = get(DigestType.AGENT_CLUSTERS, f"account:{namespace}", namespace=namespace)
7027
+ except Exception: # noqa: BLE001 - a failed lookup means "unknown", not "fresh"
7028
+ logger.debug("Cluster digest lookup failed", exc_info=True)
7029
+ return None
7030
+ return getattr(digest, "compiled_at", None) if digest is not None else None
7031
+
7032
+
7033
+ def _cluster_compile_is_fresh(adapter: Any, namespace: str, window_key: str) -> bool:
7034
+ """Whether a compile finished inside the reuse window, on any instance."""
7035
+ compiled_at = _cluster_digest_compiled_at(adapter, namespace)
7036
+ if compiled_at is not None:
7037
+ if compiled_at.tzinfo is None:
7038
+ compiled_at = compiled_at.replace(tzinfo=UTC)
7039
+ age = (datetime.now(UTC) - compiled_at).total_seconds()
7040
+ return age < _CLUSTER_RECOMPUTE_MIN_INTERVAL_S
7041
+ last = _cluster_recompute_last.get(window_key)
7042
+ return last is not None and time.monotonic() - last < _CLUSTER_RECOMPUTE_MIN_INTERVAL_S
6852
7043
 
6853
7044
 
6854
7045
  def _recompute_window_key(request: Request, namespace: str) -> str:
@@ -6882,13 +7073,16 @@ def recompute_clusters(
6882
7073
  force: bool = False,
6883
7074
  _auth: str | None = Depends(verify_api_key),
6884
7075
  ) -> dict[str, Any]:
6885
- """Trigger recomputation of agent clusters.
6886
-
6887
- Runs on the threadpool (plain ``def``): the compile is CPU-bound Python and
6888
- used to freeze the event loop for its whole duration. ``force=true`` skips
6889
- the reuse window but still waits its turn behind a compile in flight. The
6890
- window is per tenant account; the lock is per process, because the compile
6891
- is what pins the core.
7076
+ """Schedule a recomputation of agent clusters and return.
7077
+
7078
+ The caller reads the result through ``/agent-groups/suggestions``, which
7079
+ is what it did after waiting here before; the compile is CPU-bound Python
7080
+ that ran inside this request for minutes on a large account, with the
7081
+ Agents page POSTing it on every mount. The reuse window is the stored
7082
+ digest's ``compiled_at``, so it holds across every instance serving the
7083
+ account — a per-process window let each of twelve instances compile the
7084
+ same account once. ``force=true`` skips the window but still yields to a
7085
+ compile in flight in this process.
6892
7086
  """
6893
7087
  try:
6894
7088
  from amfs_cortex.compiler import DigestCompiler
@@ -6908,16 +7102,27 @@ def recompute_clusters(
6908
7102
  ns = mem.namespace
6909
7103
  window_key = _recompute_window_key(request, ns)
6910
7104
  with _cluster_recompute_lock:
6911
- last = _cluster_recompute_last.get(window_key)
6912
- if (
6913
- not force
6914
- and last is not None
6915
- and time.monotonic() - last < _CLUSTER_RECOMPUTE_MIN_INTERVAL_S
6916
- ):
7105
+ if window_key in _cluster_recompute_inflight:
7106
+ return {"ok": True, "skipped": "in_progress"}
7107
+ if not force and _cluster_compile_is_fresh(adapter, ns, window_key):
6917
7108
  return {"ok": True, "skipped": "recent"}
6918
- DigestCompiler(adapter=adapter, namespace=ns).compile(f"cluster:account:{ns}")
6919
- _cluster_recompute_last[window_key] = time.monotonic()
6920
- return {"ok": True}
7109
+ _cluster_recompute_inflight.add(window_key)
7110
+
7111
+ def _compile() -> None:
7112
+ try:
7113
+ DigestCompiler(adapter=adapter, namespace=ns).compile(f"cluster:account:{ns}")
7114
+ with _cluster_recompute_lock:
7115
+ _cluster_recompute_last[window_key] = time.monotonic()
7116
+ except Exception:
7117
+ logger.exception("Agent cluster compile failed for %s", window_key)
7118
+ finally:
7119
+ with _cluster_recompute_lock:
7120
+ _cluster_recompute_inflight.discard(window_key)
7121
+
7122
+ # The copied context carries the request's tenant into the thread, the
7123
+ # way every other background write here does.
7124
+ _bg_executor.submit(contextvars.copy_context().run, _compile)
7125
+ return {"ok": True, "scheduled": True}
6921
7126
 
6922
7127
 
6923
7128
  # ──────────────────────────────────────────────────────────────────────
@@ -8506,29 +8711,132 @@ def graph_backfill(
8506
8711
  # ──────────────────────────────────────────────────────────────────────
8507
8712
 
8508
8713
 
8509
- def _compute_tiers(entries: list) -> tuple[dict[str, int], dict[str, float]]:
8510
- """Score entries and assign HMO tiers (Hot/Warm/Archive)."""
8511
- 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)
8512
8722
 
8513
- scorer = PriorityScorer()
8514
- assigner = TierAssigner()
8515
- return assigner.assign_with_scores(entries, scorer)
8516
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)
8517
8730
 
8518
- def _tiered_entries(
8519
- mem: AgentMemory, vis: Any | None, agent_id: str | None
8520
- ) -> tuple[list[MemoryEntry], tuple[dict[str, int], dict[str, float]]]:
8521
- """The entries a tiers page scores, and their tiers and scores.
8522
8731
 
8523
- The tiering is a Python scorer over the whole visible set, so the set has
8524
- to be loaded; this loads only the named agent's rows when there is one
8525
- and runs the load, the visibility pass and the scoring together off the
8526
- event loop. Synchronous: call it via ``_offload``.
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
8740
+
8741
+
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``.
8527
8770
  """
8528
- entries = _entries_by_agent(mem, agent_id) if agent_id else mem.list()
8529
- if vis is not None:
8530
- entries = vis.filter_entries(entries)
8531
- 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
+ }
8532
8840
 
8533
8841
 
8534
8842
  @app.get("/api/v1/pro/tiers/distribution")
@@ -8537,32 +8845,36 @@ async def tiers_distribution(
8537
8845
  agent_id: str | None = Query(None),
8538
8846
  _auth: str | None = Depends(verify_api_key),
8539
8847
  ) -> dict[str, Any]:
8540
- """Return HMO tier distribution (Hot / Warm / Archive)."""
8541
- entries, (tiers, scores) = await _offload(
8542
- _db_executor, _tiered_entries, _get_memory(), _active_visibility_filter(request), agent_id
8543
- )
8544
-
8545
- hot = warm = archive = scored_count = 0
8546
- score_sum = 0.0
8547
- for key, tier in tiers.items():
8548
- if tier == 1:
8549
- hot += 1
8550
- elif tier == 2:
8551
- warm += 1
8552
- else:
8553
- archive += 1
8554
- s = scores.get(key)
8555
- if s is not None:
8556
- scored_count += 1
8557
- 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
8558
8869
 
8870
+ hot, warm, archive = _tier_split(total)
8559
8871
  return {
8560
- "total": len(entries),
8872
+ "total": total,
8561
8873
  "hot": hot,
8562
8874
  "warm": warm,
8563
8875
  "archive": archive,
8564
- "scored": scored_count,
8565
- "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,
8566
8878
  }
8567
8879
 
8568
8880
 
@@ -8574,28 +8886,28 @@ async def tiers_entries(
8574
8886
  agent_id: str | None = Query(None),
8575
8887
  _auth: str | None = Depends(verify_api_key),
8576
8888
  ) -> list[dict[str, Any]]:
8577
- """Return entries for a given HMO tier as a flat array."""
8578
- entries, (tier_map, score_map) = await _offload(
8579
- _db_executor, _tiered_entries, _get_memory(), _active_visibility_filter(request), agent_id
8580
- )
8581
-
8582
- filtered = [e for e in entries if tier_map.get(e.entry_key) == tier]
8583
- 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]
8584
8904
 
8585
- return [
8586
- {
8587
- "entity_path": e.entity_path,
8588
- "key": e.key,
8589
- "confidence": e.confidence,
8590
- "tier": tier,
8591
- "priority_score": round(score_map.get(e.entry_key, 0.0), 6),
8592
- "recall_count": getattr(e, "recall_count", 0),
8593
- "importance_score": getattr(e, "importance_score", None),
8594
- "written_at": e.provenance.written_at.isoformat(),
8595
- "agent_id": e.provenance.agent_id,
8596
- }
8597
- for e in filtered[:limit]
8598
- ]
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]]
8599
8911
 
8600
8912
 
8601
8913
  # ──────────────────────────────────────────────────────────────────────
@@ -9005,9 +9317,20 @@ def list_cortex_digests(
9005
9317
  request: Request,
9006
9318
  digest_type: str | None = Query(None),
9007
9319
  scope: str | None = Query(None),
9320
+ written_by: str | None = Query(None, max_length=200),
9321
+ limit: int | None = Query(None, ge=1, le=500),
9008
9322
  _auth: str | None = Depends(verify_api_key),
9009
9323
  ) -> dict[str, Any]:
9010
- """List compiled digests, optionally filtered by type and scope."""
9324
+ """List compiled digests, optionally filtered by type and scope.
9325
+
9326
+ The filters and ``limit`` (most recently compiled first) apply in SQL: a
9327
+ page asking for one agent's brief gets that brief, not every brief on the
9328
+ account to pick its own out of. ``written_by`` keeps the digests whose
9329
+ scope is an entity that agent has written to — an agent page's "briefed
9330
+ with" list without every entity digest on the account. A restricted
9331
+ caller's visibility is applied after, so with ``limit`` such a caller may
9332
+ receive fewer.
9333
+ """
9011
9334
  try:
9012
9335
  from amfs_postgres.adapter import PostgresAdapter
9013
9336
  from amfs_core.models import DigestType
@@ -9017,9 +9340,13 @@ def list_cortex_digests(
9017
9340
  if isinstance(adapter, PostgresAdapter):
9018
9341
  dt = DigestType(digest_type) if digest_type else None
9019
9342
  namespace = getattr(adapter, "_namespace", "default")
9020
- digests = adapter.list_digests(digest_type=dt, namespace=namespace)
9021
- if scope:
9022
- digests = [d for d in digests if d.scope == scope]
9343
+ digests = adapter.list_digests(
9344
+ digest_type=dt,
9345
+ namespace=namespace,
9346
+ scope=scope or None,
9347
+ written_by=written_by or None,
9348
+ limit=limit,
9349
+ )
9023
9350
 
9024
9351
  vis = _get_visibility_filter(request)
9025
9352
  if vis is not None and vis.should_filter():
@@ -9229,6 +9556,46 @@ def list_consolidation_proposals(
9229
9556
  }
9230
9557
 
9231
9558
 
9559
+ _CONSOLIDATION_READY_MIN_ENTRIES = 10
9560
+ _CONSOLIDATION_READY_LIMIT = 10
9561
+
9562
+
9563
+ def _consolidation_ready_entities(request: Request, adapter: Any) -> list[str]:
9564
+ """Entity paths with enough entries to consolidate, largest first.
9565
+
9566
+ One GROUP BY where the adapter has it and the caller's visibility is a
9567
+ SQL predicate (or absent); otherwise the rule runs over loaded entries,
9568
+ which is the only correct answer for a filter SQL cannot express.
9569
+ """
9570
+ ready = getattr(adapter, "consolidation_ready_entities", None)
9571
+ scope, py_vis = _visibility_scope(request)
9572
+ if callable(ready) and py_vis is None:
9573
+ try:
9574
+ kwargs: dict[str, Any] = {
9575
+ "min_entries": _CONSOLIDATION_READY_MIN_ENTRIES,
9576
+ "limit": _CONSOLIDATION_READY_LIMIT,
9577
+ }
9578
+ if scope is not None:
9579
+ kwargs["scope"] = scope
9580
+ return list(ready(**kwargs))
9581
+ except TypeError:
9582
+ pass # an adapter without SQL scoping; reduce over its rows
9583
+ entries = adapter.list()
9584
+ vis = py_vis if py_vis is not None else _active_visibility_filter(request)
9585
+ if vis is not None:
9586
+ entries = vis.filter_entries(entries)
9587
+ entity_counts: dict[str, int] = {}
9588
+ for e in entries:
9589
+ entity_counts[e.entity_path] = entity_counts.get(e.entity_path, 0) + 1
9590
+ out: list[str] = []
9591
+ for ep, count in sorted(entity_counts.items(), key=lambda x: (-x[1], x[0])):
9592
+ if count >= _CONSOLIDATION_READY_MIN_ENTRIES:
9593
+ out.append(ep)
9594
+ if len(out) >= _CONSOLIDATION_READY_LIMIT:
9595
+ break
9596
+ return out
9597
+
9598
+
9232
9599
  @app.get("/api/v1/cortex/consolidation/status")
9233
9600
  def consolidation_status(
9234
9601
  request: Request,
@@ -9265,17 +9632,7 @@ def consolidation_status(
9265
9632
 
9266
9633
  entities_ready: list[str] = []
9267
9634
  try:
9268
- entries = adapter.list()
9269
- if vis is not None:
9270
- entries = vis.filter_entries(entries)
9271
- entity_counts: dict[str, int] = {}
9272
- for e in entries:
9273
- entity_counts[e.entity_path] = entity_counts.get(e.entity_path, 0) + 1
9274
- for ep, count in sorted(entity_counts.items(), key=lambda x: -x[1]):
9275
- if count >= 10:
9276
- entities_ready.append(ep)
9277
- if len(entities_ready) >= 10:
9278
- break
9635
+ entities_ready = _consolidation_ready_entities(request, adapter)
9279
9636
  except Exception:
9280
9637
  pass
9281
9638