Purpose-built scripts and the TKTail workflow - the source
datasets/generate.py
SHA-256 (LF line endings, as in the source ZIP): 352edd7206021c26dcc64e82a88cb700c2c5fb0b217a4a8e0122bb767c7cec3f · MIT license (the benchmark suite only)
#!/usr/bin/env python3
"""Deterministic synthetic logs for the TKTail competitive benchmark (competitive-bench-v1).
python generate.py --config configs/iis-1gb.json --out <folder>
writes <folder>/<name>.log and <folder>/<name>.expected.json (the ground truth of every scenario, computed while the
data is written - independent of every implementation that is measured) and prints the file's size and SHA-256.
Everything is synthetic: client addresses come from the documentation ranges (RFC 5737), accounts are "acct-NNNN",
servers and paths are invented. The random numbers come from SplitMix64 (below) - a fully specified generator, so the
same seed gives the same bytes on every machine and Python version.
"""
import argparse
import datetime
import hashlib
import json
import os
import sys
GENERATOR_VERSION = 1
MASK = (1 << 64) - 1
class SplitMix64:
"""SplitMix64 (Steele, Lea, Flood 2014). next() -> 64-bit integer; below(n) -> next() % n (the modulo bias is part
of the definition: what matters is that every reproduction uses the same numbers)."""
def __init__(self, seed):
self.state = seed & MASK
def next(self):
self.state = (self.state + 0x9E3779B97F4A7C15) & MASK
z = self.state
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK
return z ^ (z >> 31)
def below(self, n):
return self.next() % n
def chance(self, per_million):
return self.next() % 1_000_000 < per_million
def top(counter, n):
"""The top n (key, count) pairs: count descending, then key ascending - the order every implementation reports."""
return [[k, c] for k, c in sorted(counter.items(), key=lambda kv: (-kv[1], kv[0]))[:n]]
def distinct_top(counter, n):
"""True when the top n counts are all different and differ from the next one (no tie decides membership)."""
counts = sorted(counter.values(), reverse=True)[: n + 1]
return len(counts) <= n or all(a > b for a, b in zip(counts, counts[1:]))
# ---------------------------------------------------------------- IIS W3C (the IIS default fields plus sc-bytes)
IIS_FIELDS = ['date', 'time', 's-ip', 'cs-method', 'cs-uri-stem', 'cs-uri-query', 's-port', 'cs-username', 'c-ip',
'cs(User-Agent)', 'cs(Referer)', 'sc-status', 'sc-substatus', 'sc-win32-status', 'sc-bytes', 'time-taken']
AGENTS = ['Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)', 'Mozilla/5.0+(Macintosh;+Intel+Mac+OS+X+14_5)',
'curl/8.9.1', 'okhttp/4.12.0', 'Go-http-client/1.1', 'python-requests/2.32.3']
AREAS = ['orders', 'payments', 'inventory', 'customers', 'shipping', 'catalog', 'auth', 'reports', 'search', 'cart']
ACTIONS = ['list', 'get', 'create', 'update', 'status', 'export', 'history', 'summary', 'validate', 'quote',
'refresh', 'lookup', 'cancel', 'confirm', 'sync', 'audit', 'upload', 'download', 'preview', 'batch',
'items', 'totals', 'events', 'notes', 'limits', 'metrics', 'health', 'config', 'tokens', 'sessions']
URIS = [f'/api/v2/{a}/{b}' for a in AREAS for b in ACTIONS] # 300 stems
CLIENTS = [f'203.0.113.{i}' for i in range(1, 255)] + [f'198.51.100.{i}' for i in range(1, 255)] + \
[f'192.0.2.{i}' for i in range(1, 255)] # 762 documentation addresses (RFC 5737)
OFFENDERS = [CLIENTS[(i * 37 + 11) % len(CLIENTS)] for i in range(15)] # the clients behind most server errors
HOT_URIS = [URIS[(i * 29 + 7) % len(URIS)] for i in range(12)]
def iis(cfg, out):
rng = SplitMix64(cfg['seed'])
target = cfg['targetBytes']
per_second = cfg['recordsPerSecond']
start = datetime.datetime.fromisoformat(cfg['start'])
exp = {'records': 0, 'count5xx': 0, 'count503': 0, 'count503Post': 0, 'countTimeTakenGe1000': 0}
by_ip_5xx, by_uri_5xx, by_minute_5xx, by_ip_503, by_ip_503post = {}, {}, {}, {}, {}
written = 0
second = 0
stamp_second = -1
date_text = time_text = minute_key = ''
# Weights of the offenders: 15^2 .. 1^2 - far apart, so the top 10 is never decided by a tie.
offender_weights = [(15 - i) ** 2 for i in range(15)]
offender_total = sum(offender_weights)
hot_weights = [(12 - i) ** 2 for i in range(12)] # the URL paths behind most server errors, likewise
hot_total = sum(hot_weights)
with open(out, 'wb') as f:
header = ('#Software: Microsoft Internet Information Services 10.0\r\n#Version: 1.0\r\n'
f'#Date: {start:%Y-%m-%d %H:%M:%S}\r\n#Fields: {" ".join(IIS_FIELDS)}\r\n').encode('ascii')
f.write(header)
written += len(header)
buf = []
buffered = 0
while written + buffered < target:
if rng.below(1_000_000) < 1_000_000 // per_second:
second += 1
if second != stamp_second:
stamp_second = second
t = start + datetime.timedelta(seconds=second)
date_text, time_text = f'{t:%Y-%m-%d}', f'{t:%H:%M:%S}'
minute_key = f'{t:%Y-%m-%dT%H:%M}'
r = rng.below(1000)
if r < 920:
status = 200
elif r < 950:
status = 304
elif r < 970:
status = 404
else:
s = rng.below(10)
status = 500 if s < 5 else 502 if s < 7 else 503
error = status >= 500
if error and rng.below(100) < 55:
pick = rng.below(offender_total)
k = 0
while pick >= offender_weights[k]:
pick -= offender_weights[k]
k += 1
client = OFFENDERS[k]
else:
client = CLIENTS[rng.below(len(CLIENTS))]
if error and rng.below(100) < 50:
pick = rng.below(hot_total)
k = 0
while pick >= hot_weights[k]:
pick -= hot_weights[k]
k += 1
uri = HOT_URIS[k]
else:
uri = URIS[rng.below(len(URIS))]
method = 'POST' if rng.below(5) == 0 else 'GET'
query = f'id={rng.below(1_000_000)}' if rng.below(3) == 0 else '-'
user = f'acct-{rng.below(5000):04d}' if rng.below(4) else '-'
agent = AGENTS[rng.below(len(AGENTS))]
if rng.below(1000) < (300 if error else 20):
taken = 1000 + rng.below(29_000)
else:
taken = 2 + rng.below(240)
size = (200 + rng.below(20_000)) if status == 200 else (100 + rng.below(900))
win32 = 64 if status == 502 else 0
line = (f'{date_text} {time_text} 10.20.30.40 {method} {uri} {query} 443 {user} {client} {agent} - '
f'{status} 0 {win32} {size} {taken}\r\n')
buf.append(line)
buffered += len(line)
exp['records'] += 1
if taken >= 1000:
exp['countTimeTakenGe1000'] += 1
if error:
exp['count5xx'] += 1
by_ip_5xx[client] = by_ip_5xx.get(client, 0) + 1
by_uri_5xx[uri] = by_uri_5xx.get(uri, 0) + 1
by_minute_5xx[minute_key] = by_minute_5xx.get(minute_key, 0) + 1
if status == 503:
exp['count503'] += 1
by_ip_503[client] = by_ip_503.get(client, 0) + 1
if method == 'POST':
exp['count503Post'] += 1
by_ip_503post[client] = by_ip_503post.get(client, 0) + 1
if buffered >= 4 * 1024 * 1024:
data = ''.join(buf).encode('ascii')
f.write(data)
written += len(data)
buf, buffered = [], 0
if buf:
data = ''.join(buf).encode('ascii')
f.write(data)
written += len(data)
exp['top10ClientIp5xx'] = top(by_ip_5xx, 10)
exp['top10UriStem5xx'] = top(by_uri_5xx, 10)
exp['top10ClientIp503'] = top(by_ip_503, 10)
exp['top10ClientIp503Post'] = top(by_ip_503post, 10)
exp['perMinute5xx'] = sorted([k, v] for k, v in by_minute_5xx.items())
exp['topIsUnambiguous'] = {'top10ClientIp5xx': distinct_top(by_ip_5xx, 10), 'top10UriStem5xx': distinct_top(by_uri_5xx, 10),
'top10ClientIp503': distinct_top(by_ip_503, 10), 'top10ClientIp503Post': distinct_top(by_ip_503post, 10)}
return exp
# ---------------------------------------------------------------- an application log (multi-line records)
LOGGERS = ['Orders', 'Payments', 'Gateway', 'Inventory', 'Auth']
INFO = ['request completed', 'order accepted', 'cache refreshed', 'session started', 'stock reserved']
WARN = ['retry scheduled after connection reset', 'slow downstream call', 'queue depth above target',
'token refresh delayed', 'operation canceled by client']
FAIL = ['payment failed', 'order rejected', 'upstream timeout', 'database call failed', 'write conflict']
FRAMES = [' at Orders.Service.Charge(Order order)', ' at Orders.Service.Submit(Order order)',
' at Payments.Gateway.Authorize(Payment payment)', ' at Shared.Retry.Execute[T](Func`1 action)',
' at Shared.Db.Command.Execute()', ' at Program.Main(String[] args)']
def applog(cfg, out):
rng = SplitMix64(cfg['seed'])
target = cfg['targetBytes']
start = datetime.datetime.fromisoformat(cfg['start'])
exp = {'records': 0, 'lines': 0, 'linesWithERROR': 0, 'recordsElapsedGe1000': 0}
ms = 0
written = 0
buf = []
buffered = 0
with open(out, 'wb') as f:
while written + buffered < target:
ms += rng.below(40)
t = start + datetime.timedelta(milliseconds=ms)
r = rng.below(1000)
level = 'INFO ' if r < 850 else 'WARN ' if r < 940 else 'ERROR' if r < 990 else 'DEBUG'
logger = LOGGERS[rng.below(len(LOGGERS))]
account = f'acct-{rng.below(5000):04d}'
e = rng.below(100_000)
if e < 50:
elapsed = 1_000_000 # exactly 1000.000 ms - the boundary
elif e < 100:
elapsed = 999_999 # 999.999 ms - just below it
elif e < (12_000 if level == 'ERROR' else 3_000):
elapsed = 1_000_000 + rng.below(9_000_000) # 1 to 10 s
else:
elapsed = 1_000 + rng.below(499_000) # 1 ms to 0.5 s
if level == 'ERROR':
text = f'{FAIL[rng.below(len(FAIL))]} account={account} code=E{rng.below(90) + 10}'
elif level == 'WARN ':
text = f'{WARN[rng.below(len(WARN))]} account={account}'
else:
text = f'{INFO[rng.below(len(INFO))]} account={account} status=200'
line = (f'{t:%Y-%m-%d %H:%M:%S}.{t.microsecond // 1000:03d} {level} [{logger}] {text} '
f'elapsed: {elapsed // 1000}.{elapsed % 1000:03d}ms bytes={rng.below(50_000)}\n')
buf.append(line)
buffered += len(line)
exp['records'] += 1
exp['lines'] += 1
if level == 'ERROR':
exp['linesWithERROR'] += 1
if elapsed >= 1_000_000:
exp['recordsElapsedGe1000'] += 1
if level == 'ERROR' and rng.below(10) < 3:
frames = 2 + rng.below(4)
exception = 'System.TimeoutException: the operation timed out\n'
buf.append(exception)
buffered += len(exception)
for _ in range(frames):
frame = FRAMES[rng.below(len(FRAMES))] + '\n'
buf.append(frame)
buffered += len(frame)
exp['lines'] += 1 + frames
if buffered >= 4 * 1024 * 1024:
data = ''.join(buf).encode('ascii')
f.write(data)
written += len(data)
buf, buffered = [], 0
if buf:
data = ''.join(buf).encode('ascii')
f.write(data)
written += len(data)
return exp
def sha256_of(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
while chunk := f.read(8 * 1024 * 1024):
h.update(chunk)
return h.hexdigest()
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--config', required=True)
ap.add_argument('--out', required=True, help='the folder the dataset and its expected results are written to')
args = ap.parse_args()
with open(args.config, encoding='utf-8') as f:
cfg = json.load(f)
os.makedirs(args.out, exist_ok=True)
log = os.path.join(args.out, cfg['name'] + '.log')
started = datetime.datetime.now()
expected = (iis if cfg['kind'] == 'iis' else applog)(cfg, log)
size = os.path.getsize(log)
digest = sha256_of(log)
manifest = {'dataset': cfg['name'], 'generatorVersion': GENERATOR_VERSION, 'config': cfg, 'bytes': size,
'sha256': digest, 'expected': expected}
if 'sha256' in cfg and cfg['sha256'] != digest:
print(f'{cfg["name"]}: SHA-256 {digest} differs from the published {cfg["sha256"]}', file=sys.stderr)
return 2
with open(os.path.join(args.out, cfg['name'] + '.expected.json'), 'w', encoding='utf-8', newline='\n') as f:
json.dump(manifest, f, indent=1)
f.write('\n')
seconds = (datetime.datetime.now() - started).total_seconds()
print(f'{cfg["name"]}: {size:,} bytes, {expected["records"]:,} records, sha256 {digest} ({seconds:.0f} s)')
return 0
if __name__ == '__main__':
sys.exit(main())