amfs-http-server 0.3.61__tar.gz → 0.3.62__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.62
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.62"
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
  # ──────────────────────────────────────────────────────────────────────
@@ -9005,9 +9210,20 @@ def list_cortex_digests(
9005
9210
  request: Request,
9006
9211
  digest_type: str | None = Query(None),
9007
9212
  scope: str | None = Query(None),
9213
+ written_by: str | None = Query(None, max_length=200),
9214
+ limit: int | None = Query(None, ge=1, le=500),
9008
9215
  _auth: str | None = Depends(verify_api_key),
9009
9216
  ) -> dict[str, Any]:
9010
- """List compiled digests, optionally filtered by type and scope."""
9217
+ """List compiled digests, optionally filtered by type and scope.
9218
+
9219
+ The filters and ``limit`` (most recently compiled first) apply in SQL: a
9220
+ page asking for one agent's brief gets that brief, not every brief on the
9221
+ account to pick its own out of. ``written_by`` keeps the digests whose
9222
+ scope is an entity that agent has written to — an agent page's "briefed
9223
+ with" list without every entity digest on the account. A restricted
9224
+ caller's visibility is applied after, so with ``limit`` such a caller may
9225
+ receive fewer.
9226
+ """
9011
9227
  try:
9012
9228
  from amfs_postgres.adapter import PostgresAdapter
9013
9229
  from amfs_core.models import DigestType
@@ -9017,9 +9233,13 @@ def list_cortex_digests(
9017
9233
  if isinstance(adapter, PostgresAdapter):
9018
9234
  dt = DigestType(digest_type) if digest_type else None
9019
9235
  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]
9236
+ digests = adapter.list_digests(
9237
+ digest_type=dt,
9238
+ namespace=namespace,
9239
+ scope=scope or None,
9240
+ written_by=written_by or None,
9241
+ limit=limit,
9242
+ )
9023
9243
 
9024
9244
  vis = _get_visibility_filter(request)
9025
9245
  if vis is not None and vis.should_filter():
@@ -9229,6 +9449,46 @@ def list_consolidation_proposals(
9229
9449
  }
9230
9450
 
9231
9451
 
9452
+ _CONSOLIDATION_READY_MIN_ENTRIES = 10
9453
+ _CONSOLIDATION_READY_LIMIT = 10
9454
+
9455
+
9456
+ def _consolidation_ready_entities(request: Request, adapter: Any) -> list[str]:
9457
+ """Entity paths with enough entries to consolidate, largest first.
9458
+
9459
+ One GROUP BY where the adapter has it and the caller's visibility is a
9460
+ SQL predicate (or absent); otherwise the rule runs over loaded entries,
9461
+ which is the only correct answer for a filter SQL cannot express.
9462
+ """
9463
+ ready = getattr(adapter, "consolidation_ready_entities", None)
9464
+ scope, py_vis = _visibility_scope(request)
9465
+ if callable(ready) and py_vis is None:
9466
+ try:
9467
+ kwargs: dict[str, Any] = {
9468
+ "min_entries": _CONSOLIDATION_READY_MIN_ENTRIES,
9469
+ "limit": _CONSOLIDATION_READY_LIMIT,
9470
+ }
9471
+ if scope is not None:
9472
+ kwargs["scope"] = scope
9473
+ return list(ready(**kwargs))
9474
+ except TypeError:
9475
+ pass # an adapter without SQL scoping; reduce over its rows
9476
+ entries = adapter.list()
9477
+ vis = py_vis if py_vis is not None else _active_visibility_filter(request)
9478
+ if vis is not None:
9479
+ entries = vis.filter_entries(entries)
9480
+ entity_counts: dict[str, int] = {}
9481
+ for e in entries:
9482
+ entity_counts[e.entity_path] = entity_counts.get(e.entity_path, 0) + 1
9483
+ out: list[str] = []
9484
+ for ep, count in sorted(entity_counts.items(), key=lambda x: (-x[1], x[0])):
9485
+ if count >= _CONSOLIDATION_READY_MIN_ENTRIES:
9486
+ out.append(ep)
9487
+ if len(out) >= _CONSOLIDATION_READY_LIMIT:
9488
+ break
9489
+ return out
9490
+
9491
+
9232
9492
  @app.get("/api/v1/cortex/consolidation/status")
9233
9493
  def consolidation_status(
9234
9494
  request: Request,
@@ -9265,17 +9525,7 @@ def consolidation_status(
9265
9525
 
9266
9526
  entities_ready: list[str] = []
9267
9527
  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
9528
+ entities_ready = _consolidation_ready_entities(request, adapter)
9279
9529
  except Exception:
9280
9530
  pass
9281
9531