about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-27 10:41:36 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-27 10:41:36 +0000
commit465fcc0bd08495c0a702b94e002a425115a0bab3 (patch)
tree57f38d17265880dd4bc753ae8727a04b515d2013
parent20657e9f1c3afd6fea826a1633860a7140336651 (diff)
downloadgenenetwork4-465fcc0bd08495c0a702b94e002a425115a0bab3.tar.gz
gn4-log: show the usage fields, and count datasets and queries
The table grows a short suffix only when a line has them (dataset=... source=...
engine=... run=..., or q="..." type=... hits=...), and --json already passed
everything through.

Two new views for the question the log could not answer before: --datasets
counts requests and distinct callers per dataset and source (what is used, by
how many separate people), and --queries counts search terms. Both verified
against a synthetic file and a week of real lines.
-rwxr-xr-xscripts/gn4-log.py69
1 files changed, 69 insertions, 0 deletions
diff --git a/scripts/gn4-log.py b/scripts/gn4-log.py
index a14e653..c4cf3b0 100755
--- a/scripts/gn4-log.py
+++ b/scripts/gn4-log.py
@@ -25,6 +25,15 @@ Use it on a process log or a proxy log that carries `x-gn4-user`:
     scripts/gn4-log.py -f log.jsonl --json          # enriched JSON, for jq
     scripts/gn4-log.py -f log.jsonl --summary       # who ran what, counted
 
+A compute request names its panel in its *body*, not its path, so the line
+carries what the handler recorded about the work (`crate::usage`): `dataset`,
+`group`, `source`, `trait`, `engine`, `cached`, `run`, and on `/search` the
+query itself as `q` (the path has no query string on purpose). The table shows
+them in a short suffix; `--datasets` and `--queries` count them:
+
+    scripts/gn4-log.py -f log.jsonl --since 2026-11-20 --datasets
+    scripts/gn4-log.py -f log.jsonl --queries --limit 20
+
 Lines that are not JSON (a Ruby backtrace, a GEMMA progress bar) pass through
 unchanged unless --quiet; that is deliberate, because the process log
 interleaves them and dropping them would hide the interesting failures.
@@ -150,6 +159,29 @@ def enrich(record: dict, registry: Registry, when: int | None) -> dict:
     return out
 
 
+USAGE_FIELDS = ("dataset", "group", "source", "trait", "traits", "engine", "cached", "run")
+
+
+def usage_suffix(record: dict) -> str:
+    """What the handler recorded about the work, short enough for a table.
+
+    `q` is shown quoted (it is caller text and may contain spaces); the rest
+    as `key=value`. Nothing here is a secret: see `crate::usage`.
+    """
+    parts = []
+    if record.get("q") is not None:
+        parts.append(f'q="{record["q"]}"')
+        if record.get("type"):
+            parts.append(f"type={record['type']}")
+        if record.get("hits") is not None:
+            parts.append(f"hits={record['hits']}")
+    for field in USAGE_FIELDS:
+        value = record.get(field)
+        if value not in (None, ""):
+            parts.append(f"{field}={value}")
+    return "  " + " ".join(parts) if parts else ""
+
+
 def format_line(record: dict, when: str) -> str:
     who = record.get("user") or "-"
     credential = record.get("scheme") or "-"
@@ -165,6 +197,7 @@ def format_line(record: dict, when: str) -> str:
         f"{when or '-':<19} {who:<20} {credential:<34} "
         f"{record.get('method', '-'):<6} {record.get('status', '-'):>4} "
         f"{took:>6} ms  {record.get('path', '')}"
+        f"{usage_suffix(record)}"
     )
 
 
@@ -179,6 +212,9 @@ def main() -> int:
     parser.add_argument("--grep", default=None, help="only lines containing this text (matches the raw line)")
     parser.add_argument("--json", action="store_true", help="emit enriched JSON instead of a table")
     parser.add_argument("--summary", action="store_true", help="count requests per caller and credential")
+    parser.add_argument("--datasets", action="store_true", help="count requests per dataset (and source), with the distinct callers")
+    parser.add_argument("--queries", action="store_true", help="count /search queries, most frequent first")
+    parser.add_argument("--limit", type=int, default=25, help="how many rows --datasets/--queries print (default 25)")
     parser.add_argument("--quiet", action="store_true", help="drop lines that are not request records")
     args = parser.parse_args()
 
@@ -230,6 +266,39 @@ def main() -> int:
         print(f"{len(rows):>7}  {'total':<{width}}")
         return 0
 
+    if args.datasets:
+        # The question this file was written to answer: which data is used,
+        # by how many separate callers. Computes are attributed by what the
+        # handler recorded, reads by what the path spells out.
+        counts: Counter = Counter()
+        callers: dict[tuple[str, str], set[str]] = {}
+        for _, record in rows:
+            dataset, source = record.get("dataset"), record.get("source") or "-"
+            if not dataset:
+                continue
+            counts[(dataset, source)] += 1
+            callers.setdefault((dataset, source), set()).add(record.get("user") or "-")
+        width = max((len(name) for (name, _) in counts), default=10)
+        print(f"{'requests':>8} {'callers':>7}  {'dataset':<{width}}  source")
+        for (dataset, source), count in counts.most_common(args.limit):
+            print(f"{count:>8} {len(callers[(dataset, source)]):>7}  {dataset:<{width}}  {source}")
+        unattributed = sum(1 for _, record in rows if not record.get("dataset"))
+        print(f"{len(rows) - unattributed:>8} {len({(u) for c in callers.values() for u in c}):>7}  total (plus {unattributed} with no dataset recorded)")
+        return 0
+
+    if args.queries:
+        queries: Counter = Counter()
+        callers: dict[str, set[str]] = {}
+        for _, record in rows:
+            query = record.get("q")
+            if query is None:
+                continue
+            queries[query] += 1
+            callers.setdefault(query, set()).add(record.get("user") or "-")
+        for query, count in queries.most_common(args.limit):
+            print(f"{count:>7}  {len(callers[query]):>3} callers  {query}")
+        return 0
+
     for when, record in rows:
         if args.json:
             print(json.dumps(record))