← Back to Pull requests

perf(inkless:control-plane): index and rewrite list_offsets_v1 timestamp lookups [KC-537] #799

Closed
unknown closed this pull request without merging on Oct 12, 2026 15:56 UTC
View on GitHub
unknown unknown commented on Sep 11, 2026 13:38 UTC
Author

The concrete-timestamp branch of list_offsets_v1 (the offsetsForTimes path) picks its batch with ORDER BY batch_id LIMIT 1. batches_pkey yields that order, so the planner can walk the primary key across the whole batches table with the partition and timestamp as filters, and inside plpgsql it does so on every call because the generic plan cannot see the timestamp's selectivity. With a large batches backlog, every ListOffsets then runs into statement_timeout. MAX_TIMESTAMP has a related problem: no index covers batch_timestamp(...), so it evaluates the function for every retained batch. Two Flyway migrations fix this and must ship together: V30 adds the index, and V31 rewrites the lookups so the planner has no ordered-walk plan left to pick. See the commit message for the planner reasoning.

Flyway migrations

  • V30__Batches_by_timestamp_index.sql: creates batches_by_timestamp_idx on (topic_id, partition, batch_timestamp(...)) INCLUDE (base_offset), then runs ANALYZE batches. Flyway runs it in a transaction, so the build holds a SHARE lock on batches and blocks commit_file until it finishes, during broker startup. Measured build rate is about 200k rows/s single-threaded: about 6 minutes at 70M rows and over an hour at the 1e9 rows V24 designs for. At that scale, run the CREATE INDEX CONCURRENTLY IF NOT EXISTS statement from the migration header before upgrading. The migration then only runs ANALYZE. batch_timestamp must stay LANGUAGE plpgsql, otherwise queries stop matching the stored index expression and the index goes unused. The index adds about 4 GB per 70M rows and a plpgsql call per inserted batch.

  • V31__List_offsets_min_offset_lookup.sql: CREATE OR REPLACE FUNCTION list_offsets_v1, no table lock. The two batches lookups become MIN(base_offset) over the timestamp predicate, followed by a point fetch by offset. A concrete-timestamp request first checks the oldest retained batch and skips the scan when it already qualifies. The function body is the V28 one and reads logs.deleted_at, so it cannot be hand-applied to a schema older than V28.
  • V30: new index

    CREATE INDEX IF NOT EXISTS batches_by_timestamp_idx
        ON batches (topic_id, partition, batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp))
        INCLUDE (base_offset);
    
    ANALYZE batches;
    

    V31: list_offsets_v1 changes

    Only the two batches lookups change (MAX_TIMESTAMP and the concrete timestamp). The logs-only branches are untouched. The diff is against the V28 definition, the last one before this PR.

    <details>
    <summary>Diff of <code>list_offsets_v1</code>, V28 to V31</summary>

    --- V28 list_offsets_v1
    +++ V31 list_offsets_v1
    @@ -6,6 +6,7 @@
         l_request RECORD;
         l_log RECORD;
         l_max_timestamp BIGINT = NULL;
    +    l_min_base_offset BIGINT = NULL;
         l_found_timestamp BIGINT = NULL;
         l_found_timestamp_offset BIGINT = NULL;
     BEGIN
    @@ -56,13 +57,20 @@
                 WHERE topic_id = l_request.topic_id
                     AND partition = l_request.partition;
     
    +            SELECT MIN(base_offset)
    +            INTO l_min_base_offset
    +            FROM batches
    +            WHERE topic_id = l_request.topic_id
    +                AND partition = l_request.partition
    +                AND batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp) = l_max_timestamp;
    +
                 SELECT last_offset
                 INTO l_found_timestamp_offset
                 FROM batches
                 WHERE topic_id = l_request.topic_id
                     AND partition = l_request.partition
    -                AND batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp) = l_max_timestamp
    -            ORDER BY batch_id
    +                AND last_offset >= l_min_base_offset
    +            ORDER BY last_offset
                 LIMIT 1;
     
                 IF l_found_timestamp_offset IS NULL THEN
    @@ -88,15 +96,34 @@
                 CONTINUE;
             END IF;
     
    +        -- The oldest retained batch has the smallest offset, so if it qualifies it is the answer and the
    +        -- scan below is skipped.
             SELECT batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp), base_offset
             INTO l_found_timestamp, l_found_timestamp_offset
             FROM batches
             WHERE topic_id = l_request.topic_id
                 AND partition = l_request.partition
    -            AND batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp) >= l_request.timestamp
    -        ORDER BY batch_id
    +        ORDER BY last_offset
             LIMIT 1;
     
    +        IF l_found_timestamp_offset IS NOT NULL AND l_found_timestamp < l_request.timestamp THEN
    +            SELECT MIN(base_offset)
    +            INTO l_min_base_offset
    +            FROM batches
    +            WHERE topic_id = l_request.topic_id
    +                AND partition = l_request.partition
    +                AND batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp) >= l_request.timestamp;
    +
    +            SELECT batch_timestamp(timestamp_type, batch_max_timestamp, log_append_timestamp), base_offset
    +            INTO l_found_timestamp, l_found_timestamp_offset
    +            FROM batches
    +            WHERE topic_id = l_request.topic_id
    +                AND partition = l_request.partition
    +                AND last_offset >= l_min_base_offset
    +            ORDER BY last_offset
    +            LIMIT 1;
    +        END IF;
    +
             IF l_found_timestamp_offset IS NULL THEN
                 -- -1 = org.apache.kafka.common.record.RecordBatch.NO_TIMESTAMP
                 RETURN NEXT (l_request.topic_id, l_request.partition, -1, -1, 'none')::list_offsets_response_v1;
    

    </details>

    Testing

  • ListOffsetsJobTest.timestampLookupFollowsOffsetOrderNotTimestampOrder: out-of-order timestamps across three batches. It pins that the lookup returns the first batch by offset, not the smallest qualifying timestamp. The existing MAX_TIMESTAMP and concrete-timestamp contract tests run against V31 through PostgresControlPlaneTest.

  • ListOffsetsJobTest.maxTimestampTieReturnsFirstBatchByOffset, timestampBeforeOldestBatchReturnsOldestBatch, and timestampLookupIsClampedToLogStartOffset: pin the tie case, both branches of the oldest-batch check, and the log_start_offset clamp.

  • ListOffsetsTimestampScanBenchmarkTest (@Tag("benchmark"), not run in CI): runs one seeded workload against the baseline schema (V29), V30, and V31, each in its own database through a Flyway target version. It prints per-call latency, write cost, index sizes, and EXPLAIN output.
  • How to read the benchmark: each schema prints three tables, one row per depth (25k to 400k batches in one partition). Compare schemas at the same depth, and look at how a column changes with depth more than at any single figure. In the read table, a flat column means the query ignores partition size, and a column that doubles when the depth doubles means it reads the whole partition. About 500 to 1,000 microseconds is the fixed cost of the job and the round trip, so values near that floor are "constant", not "fast". Compare V29 with V30 to price the index, since V30 and V31 share a write path. Run-to-run noise is about 10% on most figures and up to 30% on a single one. Plans come from standalone SQL and timings go through the plpgsql function, so the two can differ.

    Benchmark results

    One partition, batch i carries timestamp base + i, statistics refreshed after each seed step, local Postgres 17 container. Microseconds per list_offsets_v1 call through ListOffsetsJob at 400k retained batches. ts@start matches the first row, ts@90% matches the last 10%, ts@end+1 matches nothing.

    | schema | MAX_TIMESTAMP | ts@start | ts@90% | ts@end+1 |
    | -------- | ------------- | -------- | ------- | -------- |
    | baseline | 209,704 | 781 | 90,562 | 101,981 |
    | V30 | 592 | 590 | 95,251 | 103,372 |
    | V31 | 681 | 643 | 3,999 | 469 |

  • The baseline scans the partition twice for MAX and walks batches_pkey for the lookup. ts@start is fast only because the first row matches.

  • V30 fixes MAX. Inside the function, the generic plan still walks batches_pkey, so the two production-shaped cases barely move.

  • V31 has one plan for the lookup, a range scan of the new index. Cost follows the batches at or after the target: ts@90% reads 40k entries and ts@end+1 reads none. ts@start would read all 400k entries, so V31 first checks the oldest retained batch and skips the scan when it already qualifies.
  • Storage and write cost

    Same benchmark, 400k batches in one partition, local Postgres 17 container, one run per schema. batches sizes in MB, and the index adds 59 bytes per row (22.5 MB at 400k rows, about 4.1 GB at 70M rows).

    | index or table | baseline (V29) | V30 / V31 |
    | ------------------------------------- | -------------- | --------- |
    | heap | 48.1 | 48.1 |
    | batches_pkey | 8.6 | 8.6 |
    | batches_by_file | 3.8 | 3.8 |
    | batches_by_last_offset_covering_idx | 36.7 | 36.7 |
    | batches_by_timestamp_idx | - | 22.5 |

    The new index is 46% of the existing index total (49.1 MB) and 23% of the whole relation.

    | write path | baseline (V29) | V30 / V31 |
    | ----------------------------------- | -------------- | --------- |
    | bulk commit, microseconds per batch | 45-51 | 44-45 |
    | bulk commit, WAL bytes per batch | 456 | 559 |
    | 10-batch commit, WAL bytes | 24,575 | 25,586 |
    | 10-batch commit, milliseconds | 1.7-2.3 | 1.5-2.3 |

  • A bulk commit is one 10 MB file of 833 batches of 12 kB, and a small commit is 10 batches. WAL per batch rises by about 100 bytes (23%). Commit latency shows no change beyond run-to-run noise (about 20% on the small commits).

  • The benchmark inserts timestamps in increasing order into one partition, so every index insert lands on the right edge of the btree. A control plane with many partitions writes to many places in the index, which needs more of it cached. The benchmark does not cover that case.

  • Production sizes follow from per-row costs, not from this run. Check pg_indexes_size('batches') before and after on a staging copy.
  • Related

    Broker-side hardening for slow control-plane queries (lock removal and bounded pools) is #798. Neither PR depends on the other.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jeqo Review duration: 44778m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #799"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository