Skip to content
TKTail

Purpose-built scripts and the TKTail workflow - the source

scripts/top_from_pages.py

SHA-256 (LF line endings, as in the source ZIP): 1dd409e75b6ce97fcf79816e8286e227f82f1494c2aecda4ad3e42e792d3a412 · MIT license (the benchmark suite only)

#!/usr/bin/env python3
"""competitive-bench-v1 - the client-side half of the payload scenario's workflows A and B: an AI client saved what it
received over MCP and runs a script that counts the clients itself. This is that script.

    python top_from_pages.py <saved.json>      prints {"top": [[c-ip, count], ...]}

<saved.json> is {"kind": "records", "records": [<tktail_get_record answers>]} (workflow A: every record read whole) or
{"kind": "projectedPages", "pages": [<tktail_get_search_results answers with "fields": ["c-ip"]>]} (workflow B).
"""
import json
import sys


def clients(doc):
    if doc['kind'] == 'records':
        for answer in doc['records']:
            for field in answer['record']['fields']:
                if field['name'] == 'c-ip':
                    yield field['value']
                    break
    elif doc['kind'] == 'projectedPages':
        for page in doc['pages']:
            for result in page['results']:
                yield result['values']['c-ip']
    else:
        raise SystemExit(f'unknown kind {doc["kind"]}')


def main():
    with open(sys.argv[1], encoding='utf-8') as f:
        doc = json.load(f)
    counts = {}
    for ip in clients(doc):
        counts[ip] = counts.get(ip, 0) + 1
    top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:10]
    print(json.dumps({'top': [[k, c] for k, c in top]}))


if __name__ == '__main__':
    main()