Skip to content
TKTail

Purpose-built scripts and the TKTail workflow - the source

csharp/Program.cs

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

// competitive-bench-v1 - the C# baseline. One scenario per run:
//
//   CompetitiveBench --scenario <id> --input <log> [--repeat N] [--output <file>]
//
// prints one JSON line: the scenario's result, the time of each in-process repetition (runsMs - the first one includes
// the JIT's work), the process's CPU time and peak working set. How it reads: the file in 1 MB blocks (FileStream,
// SequentialScan), each line as a byte span - no string per line; a line is found with the vectorized IndexOf, a number
// parsed with Utf8Parser; IIS fields are located by the #Fields header, split by spaces only as far as needed; a string
// is made only for a key of a matching line. Single-threaded, as a straightforward investigation script would be.
using System.Buffers.Text;
using System.Diagnostics;
using System.Text;
using System.Text.Json;

namespace CompetitiveBench;

delegate bool LinePredicate(ReadOnlySpan<byte> line);

static class Program
{
    static int Main(string[] args)
    {
        string? scenario = null, input = null, output = null;
        int repeat = 1;
        for (int i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--scenario": scenario = args[++i]; break;
                case "--input": input = args[++i]; break;
                case "--output": output = args[++i]; break;
                case "--repeat": repeat = int.Parse(args[++i]); break;
                default: Console.Error.WriteLine($"unknown argument {args[i]}"); return 2;
            }
        }
        if (scenario is null || input is null)
        {
            Console.Error.WriteLine("CompetitiveBench --scenario <id> --input <log> [--repeat N] [--output <file>]");
            return 2;
        }
        var runs = new List<double>();
        object? result = null;
        for (int r = 0; r < repeat; r++)
        {
            var sw = Stopwatch.StartNew();
            result = Scenarios.Run(scenario, input, output);
            sw.Stop();
            runs.Add(Math.Round(sw.Elapsed.TotalMilliseconds, 3));
        }
        using var self = Process.GetCurrentProcess();
        var report = new Dictionary<string, object?>
        {
            ["implementation"] = "csharp",
            ["runtime"] = ".NET " + Environment.Version,
            ["scenario"] = scenario,
            ["result"] = result,
            ["runsMs"] = runs,
            ["cpuMs"] = Math.Round(self.TotalProcessorTime.TotalMilliseconds, 1),
            ["peakWorkingSetBytes"] = self.PeakWorkingSet64,
        };
        Console.Out.WriteLine(JsonSerializer.Serialize(report));
        return 0;
    }
}

// The lines of a file, one byte span at a time (CRLF or LF; the span is valid until the next call).
sealed class LineReader : IDisposable
{
    readonly FileStream _file;
    readonly byte[] _buffer = new byte[1 << 20];
    int _start, _end;
    bool _eof;

    public LineReader(string path) =>
        _file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1, FileOptions.SequentialScan);

    public bool Next(out ReadOnlySpan<byte> line)
    {
        while (true)
        {
            var pending = _buffer.AsSpan(_start, _end - _start);
            int nl = pending.IndexOf((byte)'\n');
            if (nl >= 0)
            {
                line = pending[..nl];
                _start += nl + 1;
                if (!line.IsEmpty && line[^1] == '\r')
                    line = line[..^1];
                return true;
            }
            if (_eof)
            {
                line = pending;
                _start = _end;
                if (!line.IsEmpty && line[^1] == '\r')
                    line = line[..^1];
                return !line.IsEmpty;
            }
            if (_start > 0)
            {
                pending.CopyTo(_buffer);
                _end -= _start;
                _start = 0;
            }
            if (_end == _buffer.Length)
                throw new InvalidDataException("a line longer than 1 MB");
            int n = _file.Read(_buffer, _end, _buffer.Length - _end);
            if (n == 0)
                _eof = true;
            else
                _end += n;
        }
    }

    public void Dispose() => _file.Dispose();
}

// A W3C extended log: field positions from its #Fields header.
sealed class IisLog : IDisposable
{
    readonly LineReader _reader;
    Dictionary<string, int> _index = new(StringComparer.Ordinal);
    public IisLog(string path) => _reader = new LineReader(path);
    public int this[string name] => _index.TryGetValue(name, out int i) ? i : throw new InvalidDataException($"no field {name}");
    public bool HasHeader => _index.Count > 0;

    // The next record; `fields` holds the ranges of its first fields.Length fields.
    public bool Next(Span<Range> fields, out ReadOnlySpan<byte> line, out int count)
    {
        while (_reader.Next(out line))
        {
            if (line.IsEmpty)
                continue;
            if (line[0] == (byte)'#')
            {
                if (line.StartsWith("#Fields: "u8))
                {
                    _index = new(StringComparer.Ordinal);
                    var names = Encoding.ASCII.GetString(line[9..]).Split(' ');
                    for (int i = 0; i < names.Length; i++)
                        _index[names[i]] = i;
                }
                continue;
            }
            count = Split(line, fields);
            return true;
        }
        count = 0;
        return false;
    }

    static int Split(ReadOnlySpan<byte> line, Span<Range> into)
    {
        int n = 0, start = 0;
        while (n < into.Length)
        {
            int space = line[start..].IndexOf((byte)' ');
            if (space < 0)
            {
                into[n++] = new Range(start, line.Length);
                break;
            }
            into[n++] = new Range(start, start + space);
            start += space + 1;
        }
        return n;
    }

    public void Dispose() => _reader.Dispose();
}

static class Scenarios
{
    public static object Run(string scenario, string path, string? output) => scenario switch
    {
        "literal-error" => new { count = CountLines(path, static line => line.IndexOf("ERROR"u8) >= 0) },
        "elapsed-ge-1000" => new { count = CountLines(path, ElapsedAtLeast1000) },
        "count-5xx" => new { count = Iis(path, null, static (s, _) => s >= 500) },
        "count-slow" => new { count = Iis(path, "time-taken", static (_, taken) => taken >= 1000) },
        "top-ip-5xx" => Top(path, "c-ip", static (s, _) => s >= 500, false),
        "top-uri-5xx" => Top(path, "cs-uri-stem", static (s, _) => s >= 500, false),
        "top-ip-503-post" => Top(path, "c-ip", static (s, _) => s == 503, true),
        "per-minute-5xx" => PerMinute(path),
        "records-503-post-full" => Records(path, output, false),
        "records-503-post-projected" => Records(path, output, true),
        _ => throw new ArgumentException($"unknown scenario {scenario}"),
    };

    static long CountLines(string path, LinePredicate predicate)
    {
        long n = 0;
        using var reader = new LineReader(path);
        while (reader.Next(out var line))
            if (predicate(line))
                n++;
        return n;
    }

    // "elapsed: 1985.000ms" - the number parsed exactly (Utf8Parser), compared with 1000.
    static bool ElapsedAtLeast1000(ReadOnlySpan<byte> line)
    {
        int at = line.IndexOf("elapsed: "u8);
        if (at < 0)
            return false;
        var rest = line[(at + 9)..];
        int ms = rest.IndexOf("ms"u8);
        return ms > 0 && Utf8Parser.TryParse(rest[..ms], out double value, out int used) && used == ms && value >= 1000;
    }

    static int Int(ReadOnlySpan<byte> s) => Utf8Parser.TryParse(s, out int v, out int used) && used == s.Length ? v : int.MinValue;

    // Records whose status (and time-taken, when named) satisfy `keep`; the count.
    static long Iis(string path, string? second, Func<int, int, bool> keep)
    {
        long n = 0;
        using var log = new IisLog(path);
        Span<Range> f = stackalloc Range[17];
        int status = -1, other = -1;
        while (log.Next(f, out var line, out int count))
        {
            if (status < 0)
            {
                status = log["sc-status"];
                other = second is null ? -1 : log[second];
            }
            int s = status < count ? Int(line[f[status]]) : int.MinValue;
            int t = other >= 0 && other < count ? Int(line[f[other]]) : 0;
            if (keep(s, t))
                n++;
        }
        return n;
    }

    // The top 10 values of `key` among the records whose status satisfies `keep` (POST only when `post`): count
    // descending, then the value (ordinal).
    static object Top(string path, string key, Func<int, int, bool> keep, bool post)
    {
        var counts = new Dictionary<string, long>(StringComparer.Ordinal);
        var lookup = counts.GetAlternateLookup<ReadOnlySpan<char>>();
        long matched = 0;
        using var log = new IisLog(path);
        Span<Range> f = stackalloc Range[17];
        Span<char> chars = stackalloc char[512];
        int status = -1, k = -1, method = -1;
        while (log.Next(f, out var line, out int count))
        {
            if (status < 0)
            {
                status = log["sc-status"];
                k = log[key];
                method = log["cs-method"];
            }
            if (status >= count || k >= count || !keep(Int(line[f[status]]), 0))
                continue;
            if (post && !line[f[method]].SequenceEqual("POST"u8))
                continue;
            matched++;
            var bytes = line[f[k]];
            int len = Encoding.ASCII.GetChars(bytes, chars);
            var value = chars[..len];
            lookup.TryGetValue(value, out long c);
            lookup[value] = c + 1;
        }
        var top = counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key, StringComparer.Ordinal).Take(10)
                        .Select(kv => new object[] { kv.Key, kv.Value }).ToList();
        return new { count = matched, top };
    }

    // Records with status >= 500 per minute (the W3C time is UTC): "2026-11-02T10:05" -> count, in time order.
    static object PerMinute(string path)
    {
        var counts = new Dictionary<string, long>(StringComparer.Ordinal);
        var lookup = counts.GetAlternateLookup<ReadOnlySpan<char>>();
        using var log = new IisLog(path);
        Span<Range> f = stackalloc Range[17];
        Span<char> minute = stackalloc char[16];
        int status = -1, date = -1, time = -1;
        while (log.Next(f, out var line, out int count))
        {
            if (status < 0)
            {
                status = log["sc-status"];
                date = log["date"];
                time = log["time"];
            }
            if (status >= count || Int(line[f[status]]) < 500)
                continue;
            var d = line[f[date]];
            var t = line[f[time]];
            if (d.Length != 10 || t.Length < 5)
                continue;
            Encoding.ASCII.GetChars(d, minute);
            minute[10] = 'T';
            Encoding.ASCII.GetChars(t[..5], minute[11..]);
            lookup.TryGetValue(minute, out long c);
            lookup[minute] = c + 1;
        }
        var buckets = counts.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => new object[] { kv.Key, kv.Value }).ToList();
        return new { buckets };
    }

    // Every 503 POST record as a JSON line: all its fields, or (projected) time, c-ip and cs-uri-stem.
    static object Records(string path, string? output, bool projected)
    {
        if (output is null)
            throw new ArgumentException("--output is required");
        long n = 0;
        using var log = new IisLog(path);
        using var file = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.Read, 1 << 16);
        using var writer = new Utf8JsonWriter(file);
        Span<Range> f = stackalloc Range[17];
        string[]? names = null;
        int status = -1, method = -1;
        while (log.Next(f, out var line, out int count))
        {
            if (status < 0)
            {
                status = log["sc-status"];
                method = log["cs-method"];
                names = new[] { "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" };
            }
            if (status >= count || Int(line[f[status]]) != 503 || !line[f[method]].SequenceEqual("POST"u8))
                continue;
            n++;
            writer.WriteStartObject();
            if (projected)
            {
                writer.WriteString("time", Encoding.ASCII.GetString(line[f[log["date"]]]) + "T" + Encoding.ASCII.GetString(line[f[log["time"]]]) + "Z");
                writer.WriteString("c-ip", line[f[log["c-ip"]]]);
                writer.WriteString("cs-uri-stem", line[f[log["cs-uri-stem"]]]);
            }
            else
                foreach (var name in names!)
                    writer.WriteString(name, line[f[log[name]]]);
            writer.WriteEndObject();
            writer.Flush();
            file.WriteByte((byte)'\n');
            writer.Reset();
        }
        writer.Flush();
        return new { count = n, bytes = file.Length };
    }
}