← Back to Pull requests

feat(inkless:delete): soft-delete diskless topics and purge in the background [KC-349] #782

Closed
unknown closed this pull request without merging on Sep 04, 2026 15:54 UTC
View on GitHub
unknown unknown commented on Sep 02, 2026 15:34 UTC
Author

The old delete_topic_v1 deleted every batch for the topic on the controller event-handler thread. A large diskless topic made DELETE_TOPICS unbounded.

DELETE_TOPICS now only stamps logs.deleted_at. Live readers treat a stamped row as gone. Brokers run TopicPurger, which calls purge_deleted_logs_v1 with a cap. FileCleaner still deletes the objects
after file.cleaner.retention.period.ms.

Controller path


delete_topic_v1 takes the live log rows FOR UPDATE, then sets deleted_at. It does not delete batches, drop logs, or mark files. ReplicaManager schedules inkless-topic-purger at topic.purger.interval.ms (default 60s).

Purge


Empty deleted logs: drop producer_state, then the log. The same per-cycle cap applies, so a wide empty topic cannot take an unbounded number of row locks. Leftovers keep more_remain true.

Logs with batches: SKIP LOCKED, drain up to the remaining budget, then drop producer_state and the log when no batches remain. The leftover probe is EXISTS (... LIMIT 1), not COUNT(*).

Files: lock affected files by file_id before the emptiness check. Two brokers can drain different partitions of one WAL file. Without that lock, neither transaction sees the other's uncommitted deletes, both skip mark_file_to_delete_v1, and the object stays uploaded with zero batches.

more_remain is a cluster-wide EXISTS(deleted_at). TopicPurger treats a cycle as idle when it deleted, purged, and marked nothing, so a SKIP LOCKED miss does not spin. A cycle is saturated when batchesDeleted reaches the cap and more_remain is still true.

producer_state


The old delete_topic_v1 never removed producer_state, and there is no foreign key to logs. A purge regression would restore that leak. Purge deletes those rows when it drops a log. V28 also deletes orphans that have no log row, because the purger only walks soft-deleted logs.

Live readers


SQL functions that join or lock logs gain deleted_at IS NULL. find_batches_v2 keeps V27's request-level l_global_bytes = 0 grant. GetLogInfo, GetProducerState, and GetCrossTierLogStart apply the same filter in Java. InMemoryControlPlane mirrors this with liveLog.

Config and metrics


topic.purger.interval.ms defaults to 60000. topic.purger.max.batches.per.cycle defaults to 20000. The same bound caps empty-log drops. 0 means unbounded. With those defaults each broker drains at most 20000 batches per minute.

TopicPurger metrics: cycle time and rate, batches/logs/files, errors, TopicPurgerCycleSaturatedRate, and TopicPurgerWorkRemain (1 when the last successful cycle left work).

FEATURES.md: DELETE_TOPICS returns after the stamp. Brokers drain in the background.

Tests


AbstractControlPlaneTest covers both backends: fence after delete(commit, find-batches, get-log-info, listOffsets, deleteRecords, enforceRetention, getCrossTierLogStart, advanceCrossTierLogStartOffset, repairDisklessLog, pruneDisklessLogs, init), capped drain, empty-log cap, and producer_state cleanup after recreate (live readers hide leaked rows).

PurgeDeletedLogsJobTest: cap, empty-log drops, producer_state on both purge loops, concurrent jobs on a shared file, and two held-open purge_deleted_logs_v1 transactions interleaved so the second blocks on the file lock and is the one that marks deleting.

TopicPurgerMockedTest: idle sleep on a SKIP LOCKED miss, saturation when the cap is hit.

Test plan


  • :storage:inkless:test --tests AbstractControlPlaneTest --tests PurgeDeletedLogsJobTest --tests TopicPurgerMockedTest --tests DeleteTopicJobTest

  • Confirm DELETE_TOPICS returns while batches still exist, then TopicPurger drains them and FileCleaner removes the objects.
  • V28 vs earlier versions

    Schema and one-off cleanup (new in V28):

    ALTER TABLE logs
    ADD COLUMN deleted_at TIMESTAMP WITH TIME ZONE;
    
    CREATE INDEX logs_by_deleted_at_idx
        ON logs (deleted_at)
        WHERE deleted_at IS NOT NULL;
    
    -- The old delete_topic_v1 dropped logs without touching producer_state. Those
    -- orphans have no log row, so the purger never sees them.
    DELETE FROM producer_state ps
    WHERE NOT EXISTS (
        SELECT 1
        FROM logs l
        WHERE l.topic_id = ps.topic_id
            AND l.partition = ps.partition
    );
    

    purge_deleted_logs_v1 is new. The replaced functions below are
    unified diffs against the last prior migration that defined each one.

    CREATE FUNCTION purge_deleted_logs_v1(
        arg_now TIMESTAMP WITH TIME ZONE,
        arg_max_batches INT
    )
    RETURNS SETOF purge_deleted_logs_response_v1 LANGUAGE plpgsql VOLATILE AS $$
    DECLARE
        l_batches_deleted BIGINT := 0;
        l_logs_purged INT := 0;
        l_files_marked INT := 0;
        l_more_remain BOOLEAN := FALSE;
        l_log RECORD;
        l_remaining BIGINT;
        l_deleted_this_log BIGINT;
        l_file_id BIGINT;
    BEGIN
        DROP TABLE IF EXISTS purge_affected_files;
        CREATE TEMPORARY TABLE purge_affected_files (
            file_id BIGINT PRIMARY KEY
        ) ON COMMIT DROP;
    
        -- Drop empty deleted logs without spending the batch budget. The same per-cycle
        -- cap still applies: a wide empty topic (many partitions, no batches) must not
        -- take an unbounded number of row locks in one transaction. Leftovers keep
        -- more_remain true for the next cycle. 0 / NULL means unbounded.
        FOR l_log IN
            SELECT topic_id, partition
            FROM logs
            WHERE deleted_at IS NOT NULL
                AND NOT EXISTS (
                    SELECT 1
                    FROM batches b
                    WHERE b.topic_id = logs.topic_id
                        AND b.partition = logs.partition
                )
            ORDER BY topic_id, partition
            LIMIT (CASE WHEN arg_max_batches > 0 THEN arg_max_batches END)
            FOR UPDATE SKIP LOCKED
        LOOP
            DELETE FROM producer_state
            WHERE topic_id = l_log.topic_id
                AND partition = l_log.partition;
            DELETE FROM logs
            WHERE topic_id = l_log.topic_id
                AND partition = l_log.partition;
            l_logs_purged := l_logs_purged + 1;
        END LOOP;
    
        l_remaining := CASE WHEN arg_max_batches > 0 THEN arg_max_batches::bigint ELSE NULL END;
    
        FOR l_log IN
            SELECT topic_id, partition
            FROM logs
            WHERE deleted_at IS NOT NULL
                AND EXISTS (
                    SELECT 1
                    FROM batches b
                    WHERE b.topic_id = logs.topic_id
                        AND b.partition = logs.partition
                )
            ORDER BY topic_id, partition
            FOR UPDATE SKIP LOCKED
        LOOP
            EXIT WHEN l_remaining IS NOT NULL AND l_remaining <= 0;
    
            l_deleted_this_log := 0;
            FOR l_file_id IN
                DELETE FROM batches
                WHERE batch_id IN (
                    SELECT batch_id
                    FROM batches
                    WHERE topic_id = l_log.topic_id
                        AND partition = l_log.partition
                    ORDER BY topic_id, partition, last_offset
                    LIMIT l_remaining
                )
                RETURNING file_id
            LOOP
                INSERT INTO purge_affected_files (file_id)
                VALUES (l_file_id)
                ON CONFLICT DO NOTHING;
                l_deleted_this_log := l_deleted_this_log + 1;
            END LOOP;
    
            l_batches_deleted := l_batches_deleted + l_deleted_this_log;
            IF l_remaining IS NOT NULL THEN
                l_remaining := l_remaining - l_deleted_this_log;
            END IF;
    
            IF NOT EXISTS (
                SELECT 1
                FROM batches
                WHERE topic_id = l_log.topic_id
                    AND partition = l_log.partition
                LIMIT 1
            ) THEN
                DELETE FROM producer_state
                WHERE topic_id = l_log.topic_id
                    AND partition = l_log.partition;
                DELETE FROM logs
                WHERE topic_id = l_log.topic_id
                    AND partition = l_log.partition;
                l_logs_purged := l_logs_purged + 1;
            END IF;
        END LOOP;
    
        -- Lock affected files in id order before the emptiness check. Two brokers can
        -- drain different partitions of the same WAL file (SKIP LOCKED on logs). Without
        -- this lock, neither transaction sees the other's uncommitted deletes, so both
        -- skip mark_file_to_delete_v1 and the file stays uploaded with zero batches.
        PERFORM 1
        FROM files
        WHERE file_id IN (SELECT file_id FROM purge_affected_files)
        ORDER BY file_id
        FOR UPDATE;
    
        SELECT COUNT(*)
        INTO l_files_marked
        FROM (
            SELECT DISTINCT af.file_id
            FROM purge_affected_files AS af
            WHERE NOT EXISTS (
                SELECT 1
                FROM batches AS b
                WHERE b.file_id = af.file_id
            )
        ) empty_files;
    
        PERFORM mark_file_to_delete_v1(arg_now, file_id)
        FROM (
            SELECT DISTINCT af.file_id
            FROM purge_affected_files AS af
            WHERE NOT EXISTS (
                SELECT 1
                FROM batches AS b
                WHERE b.file_id = af.file_id
            )
        ) empty_files;
    
        SELECT EXISTS (
            SELECT 1
            FROM logs
            WHERE deleted_at IS NOT NULL
        )
        INTO l_more_remain;
    
        RETURN NEXT (l_batches_deleted, l_logs_purged, l_files_marked, l_more_remain)::purge_deleted_logs_response_v1;
    END;
    $$
    ;
    
    -- commit_file_v1 (from V20__Logs_earliest_batch_timestamp.sql): ignore soft-deleted logs.
    

    delete_topic_v1 (was V6__Improve_understandability_of_delete_topic_v1.sql)

    --- V6__Improve_understandability_of_delete_topic_v1.sql::delete_topic_v1
    +++ V28__Soft_delete_logs.sql::delete_topic_v1
    @@ -4,43 +4,19 @@
     )
     RETURNS VOID LANGUAGE plpgsql VOLATILE AS $$
     BEGIN
    -    -- Ensure no other transaction commits or does anything else to the affected partitions while this transaction is in progress.
    +    -- Wait for in-flight commits that already hold the log row, then stamp.
    +    -- Later commits select only deleted_at IS NULL, so they see nonexistent_log.
         PERFORM
         FROM logs
         WHERE topic_id = ANY(arg_topic_ids)
    -    ORDER BY topic_id, partition  -- ordering is important to prevent deadlocks
    +        AND deleted_at IS NULL
    +    ORDER BY topic_id, partition
         FOR UPDATE;
    
    -    DROP TABLE IF EXISTS affected_files;
    -    -- Delete the affected batches and remember what files are affected.
    -    -- We need to separate deleting batches and finding empty files because if they are in the same requests as CTE,
    -    -- the query below will see the MVCC snapshot from before deleting batches.
    -    CREATE TEMPORARY TABLE affected_files
    -    ON COMMIT DROP
    -    AS
    -        WITH deleted_batches AS (
    -            DELETE FROM batches
    -            WHERE topic_id = ANY(arg_topic_ids)
    -            RETURNING file_id
    -        )
    -        SELECT file_id
    -        FROM deleted_batches;
    -
    -    DELETE FROM logs
    -    WHERE topic_id = ANY(arg_topic_ids);
    -
    -    -- Out of the affected files, select those that are now empty (i.e. no batch refers to them)
    -    -- and mark them for deletion.
    -    PERFORM mark_file_to_delete_v1(arg_now, file_id)
    -    FROM (
    -        SELECT DISTINCT af.file_id
    -        FROM affected_files AS af
    -        WHERE NOT EXISTS (
    -            SELECT 1
                FROM batches AS b
                WHERE b.file_id = af.file_id
            )
        );
    +    UPDATE logs
    +    SET deleted_at = arg_now
    +    WHERE topic_id = ANY(arg_topic_ids)
    +        AND deleted_at IS NULL;
     END;
     $$
     ;
    

    commit_file_v1 (was V20__Logs_earliest_batch_timestamp.sql)

    --- V20__Logs_earliest_batch_timestamp.sql::commit_file_v1
    +++ V28__Soft_delete_logs.sql::commit_file_v1
    @@ -32,6 +32,7 @@
             SELECT *
             FROM logs
             WHERE (topic_id, partition) IN (SELECT DISTINCT topic_id, partition FROM unnest(arg_requests))
    +            AND deleted_at IS NULL
             ORDER BY topic_id, partition  -- ordering is important to prevent deadlocks
             FOR UPDATE;
    
    @@ -194,7 +195,8 @@
             LIMIT 1
         )
         WHERE (l.topic_id, l.partition) IN (SELECT DISTINCT topic_id, partition FROM unnest(arg_requests))
    -        AND l.earliest_batch_timestamp IS NULL;
    +        AND l.earliest_batch_timestamp IS NULL
    +        AND l.deleted_at IS NULL;
    
         IF NOT EXISTS (SELECT 1 FROM batches WHERE file_id = l_new_file_id LIMIT 1) THEN
             PERFORM mark_file_to_delete_v1(arg_now, l_new_file_id);
    

    commit_file_v2 (was V20__Logs_earliest_batch_timestamp.sql)

    --- V20__Logs_earliest_batch_timestamp.sql::commit_file_v2
    +++ V28__Soft_delete_logs.sql::commit_file_v2
    @@ -48,6 +48,7 @@
             SELECT *
             FROM logs
             WHERE (topic_id, partition) IN (SELECT DISTINCT topic_id, partition FROM unnest(arg_requests))
    +            AND deleted_at IS NULL
             ORDER BY topic_id, partition  -- ordering is important to prevent deadlocks
             FOR UPDATE;
    
    @@ -233,7 +234,8 @@
             LIMIT 1
         )
         WHERE (l.topic_id, l.partition) IN (SELECT DISTINCT topic_id, partition FROM unnest(arg_requests))
    -        AND l.earliest_batch_timestamp IS NULL;
    +        AND l.earliest_batch_timestamp IS NULL
    +        AND l.deleted_at IS NULL;
    
         IF NOT EXISTS (SELECT 1 FROM batches WHERE file_id = l_new_file_id LIMIT 1) THEN
             PERFORM mark_file_to_delete_v1(arg_now, l_new_file_id);
    

    find_batches_v2 (was V27__Find_batches_request_level_min_one_message.sql)

    --- V27__Find_batches_request_level_min_one_message.sql::find_batches_v2
    +++ V28__Soft_delete_logs.sql::find_batches_v2
    @@ -29,7 +29,7 @@
                 END AS error
             FROM unnest(arg_requests) WITH ORDINALITY
                 AS r(topic_id, partition, starting_offset, max_partition_fetch_bytes, ordinality)
    -        LEFT JOIN logs l ON r.topic_id = l.topic_id AND r.partition = l.partition
    +        LEFT JOIN logs l ON r.topic_id = l.topic_id AND r.partition = l.partition AND l.deleted_at IS NULL
             ORDER BY r.ordinality
         LOOP
             IF l_request.error IS NOT NULL THEN
    

    delete_records_v1 (was V20__Logs_earliest_batch_timestamp.sql)

    --- V20__Logs_earliest_batch_timestamp.sql::delete_records_v1
    +++ V28__Soft_delete_logs.sql::delete_records_v1
    @@ -25,6 +25,7 @@
             FROM logs
             WHERE topic_id = l_request.topic_id
                 AND partition = l_request.partition
    +            AND deleted_at IS NULL
             FOR UPDATE
             INTO l_log;
    
    

    enforce_retention_v2 (was V22__Retention_enforcement_bounded_scan.sql)

    --- V22__Retention_enforcement_bounded_scan.sql::enforce_retention_v2
    +++ V28__Soft_delete_logs.sql::enforce_retention_v2
    @@ -22,6 +22,7 @@
             FROM logs
             WHERE topic_id = l_request.topic_id
                 AND partition = l_request.partition
    +            AND deleted_at IS NULL
             INTO l_log; -- NOTE: no FOR UPDATE
    
             IF NOT FOUND THEN
    @@ -63,6 +64,7 @@
                         FROM logs
                         WHERE topic_id = l_request.topic_id
                             AND partition = l_request.partition
    +                        AND deleted_at IS NULL
                     ),
                     -- Scan only the oldest (max_batches_per_request + 1) batches. The retention boundary
                     -- cannot be deeper than max_batches_per_request because the delete is capped there
    @@ -156,6 +158,7 @@
             FROM logs
             WHERE topic_id = l_request.topic_id
                 AND partition = l_request.partition
    +            AND deleted_at IS NULL
             INTO l_log
             FOR UPDATE;
    
    

    list_offsets_v1 (was V17__List_offsets_cross_tier_earliest.sql)

    --- V17__List_offsets_cross_tier_earliest.sql::list_offsets_v1
    +++ V28__Soft_delete_logs.sql::list_offsets_v1
    @@ -18,6 +18,7 @@
             FROM logs
             WHERE topic_id = l_request.topic_id
                 AND partition = l_request.partition
    +            AND deleted_at IS NULL
             INTO l_log;
    
             IF NOT FOUND THEN
    

    init_diskless_log_v1 (was V23__Init_diskless_log_authoritative_seal.sql)

    --- V23__Init_diskless_log_authoritative_seal.sql::init_diskless_log_v1
    +++ V28__Soft_delete_logs.sql::init_diskless_log_v1
    @@ -36,6 +36,7 @@
                 WHERE logs.high_watermark = 0
                     AND logs.diskless_start_offset = 0
                     AND logs.byte_size = 0
    +                AND logs.deleted_at IS NULL
                     -- A zero-offset re-init would not advance the placeholder, so leaving it alone keeps
                     -- re-initing an existing empty partition a no-op.
                     AND EXCLUDED.high_watermark > 0;
    

    repair_diskless_log_v1 (was V18__Repair_diskless_log.sql)

    --- V18__Repair_diskless_log.sql::repair_diskless_log_v1
    +++ V28__Soft_delete_logs.sql::repair_diskless_log_v1
    @@ -15,7 +15,8 @@
             UPDATE logs
                 SET diskless_start_offset = l_request.diskless_start_offset
             WHERE topic_id = l_request.topic_id
    -            AND partition = l_request.partition;
    +            AND partition = l_request.partition
    +            AND deleted_at IS NULL;
    
             l_found := FOUND;
    
    

    advance_cross_tier_log_start_v1 (was V16__Cross_tier_log_start.sql)

    --- V16__Cross_tier_log_start.sql::advance_cross_tier_log_start_v1
    +++ V28__Soft_delete_logs.sql::advance_cross_tier_log_start_v1
    @@ -1,4 +1,4 @@
    -CREATE FUNCTION advance_cross_tier_log_start_v1(
    +CREATE OR REPLACE FUNCTION advance_cross_tier_log_start_v1(
         arg_requests advance_cross_tier_log_start_request_v1[]
     )
     RETURNS SETOF advance_cross_tier_log_start_response_v1 LANGUAGE plpgsql VOLATILE AS $$
    @@ -15,6 +15,7 @@
             FROM logs
             WHERE topic_id = l_request.topic_id
                 AND partition = l_request.partition
    +            AND deleted_at IS NULL
             INTO l_log
             FOR UPDATE;
    
    

    prune_batches_below_highest_tiered_offset_v1 (was V20__Logs_earliest_batch_timestamp.sql)

    --- V20__Logs_earliest_batch_timestamp.sql::prune_batches_below_highest_tiered_offset_v1
    +++ V28__Soft_delete_logs.sql::prune_batches_below_highest_tiered_offset_v1
    @@ -19,6 +19,7 @@
                 FROM unnest(arg_requests) AS r
                 WHERE r.topic_id = l.topic_id AND r.partition = l.partition
             )
    +          AND l.deleted_at IS NULL
             ORDER BY l.topic_id, l.partition  -- ordering is important to prevent deadlocks
             FOR UPDATE;
             FOREACH l_request IN ARRAY arg_requests LOOP
    @@ -26,6 +27,7 @@
                 FROM logs
                 WHERE topic_id = l_request.topic_id
                   AND partition = l_request.partition
    +              AND deleted_at IS NULL
                 ORDER BY topic_id, partition
                 FOR UPDATE
                 INTO l_log;
    

    [KC-349]: https://aiven.atlassian.net/browse/KC-349?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: giuseppelillo Review duration: 2899m
    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 #782"
    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