import com.company.paimon.queryserver.config.CatalogSettings;
import com.company.paimon.queryserver.paimon.CatalogRegistry;
import com.company.paimon.queryserver.paimon.PaimonScanPlanner;
import com.company.paimon.queryserver.paimon.PlannedScan;
import com.company.paimon.queryserver.plan.PhysicalQuery;
import com.company.paimon.queryserver.plan.PredicateCompiler;
import com.company.paimon.queryserver.protocol.QueryLimits;
import com.company.paimon.queryserver.protocol.QueryRequest;
import com.company.paimon.queryserver.runtime.PaimonSplitSource;
import com.company.paimon.queryserver.sql.SqlPlanner;
import com.typesafe.config.ConfigFactory;
import org.apache.paimon.Snapshot;
import org.apache.paimon.catalog.Catalog;
import org.apache.paimon.catalog.CatalogContext;
import org.apache.paimon.catalog.CatalogFactory;
import org.apache.paimon.catalog.Identifier;
import org.apache.paimon.consumer.Consumer;
import org.apache.paimon.consumer.ConsumerManager;
import org.apache.paimon.data.BinaryRow;
import org.apache.paimon.data.BinaryRowWriter;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.data.InternalRow;
import org.apache.paimon.disk.IOManager;
import org.apache.paimon.fs.FileIO;
import org.apache.paimon.fs.FileStatus;
import org.apache.paimon.fs.Path;
import org.apache.paimon.operation.CleanOrphanFilesResult;
import org.apache.paimon.operation.LocalOrphanFilesClean;
import org.apache.paimon.options.ExpireConfig;
import org.apache.paimon.options.Options;
import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.schema.Schema;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.Table;
import org.apache.paimon.table.sink.CommitMessage;
import org.apache.paimon.table.sink.StreamTableCommit;
import org.apache.paimon.table.sink.StreamTableWrite;
import org.apache.paimon.table.source.ReadBuilder;
import org.apache.paimon.table.source.Split;
import org.apache.paimon.table.source.StreamTableScan;
import org.apache.paimon.types.DataTypes;
import org.apache.paimon.types.RowKind;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.stream.Materializer;
import org.apache.pekko.stream.SystemMaterializer;
import org.apache.pekko.stream.scaladsl.Sink;
import scala.Option;
import scala.collection.JavaConverters;
import scala.concurrent.Await;
import scala.concurrent.duration.Duration;

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class LabPart3To5 {

    private static Properties loadEnv(String path) throws Exception {
        Properties props = new Properties();
        try (FileInputStream fis = new FileInputStream(path)) {
            props.load(fis);
        }
        return props;
    }

    private static Map<String, String> jdbcCatalogProps(Properties env, String warehouse, String catalogKey) {
        Map<String, String> m = new LinkedHashMap<>();
        m.put("metastore", "jdbc");
        m.put("uri", env.getProperty("PAIMON_JDBC_URL"));
        m.put("jdbc.user", env.getProperty("PAIMON_USER"));
        m.put("jdbc.password", env.getProperty("PAIMON_PASSWORD"));
        m.put("catalog-key", catalogKey);
        m.put("warehouse", warehouse);
        m.put("s3.endpoint", env.getProperty("RUSTFS_ENDPOINT"));
        m.put("s3.access-key", env.getProperty("RUSTFS_ACCESS_KEY"));
        m.put("s3.secret-key", env.getProperty("RUSTFS_SECRET_KEY"));
        m.put("s3.path.style.access", "true");
        return m;
    }

    private static GenericRow orderRow(RowKind kind, String dt, long orderId, long userId, long amount, String status) {
        return GenericRow.ofKind(
            kind,
            BinaryString.fromString(dt),
            Long.valueOf(orderId),
            Long.valueOf(userId),
            Long.valueOf(amount),
            BinaryString.fromString(status)
        );
    }

    private static BinaryRow partRow(String dt) {
        BinaryRow row = new BinaryRow(1);
        BinaryRowWriter writer = new BinaryRowWriter(row);
        writer.writeString(0, BinaryString.fromString(dt));
        writer.complete();
        return row;
    }

    private static List<String> listAllObjects(FileIO fileIO, Path root) throws Exception {
        List<String> out = new ArrayList<>();
        if (!fileIO.exists(root)) return out;
        Deque<Path> stack = new ArrayDeque<>();
        stack.push(root);
        String prefix = root.toString();
        while (!stack.isEmpty()) {
            Path cur = stack.pop();
            FileStatus[] statuses = fileIO.listStatus(cur);
            if (statuses == null) continue;
            for (FileStatus st : statuses) {
                if (st.isDir()) {
                    stack.push(st.getPath());
                } else {
                    String rel = st.getPath().toString();
                    if (rel.startsWith(prefix)) rel = rel.substring(prefix.length());
                    if (rel.startsWith("/")) rel = rel.substring(1);
                    out.add(rel);
                }
            }
        }
        Collections.sort(out);
        return out;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static PlannedScan planViaPekkoServer(
            CatalogRegistry registry,
            String dbName,
            String sql,
            Option<Object> snapshotOpt,
            int maxSplits) {
        SqlPlanner sqlPlanner = new SqlPlanner(registry, 10000);
        PaimonScanPlanner scanPlanner = new PaimonScanPlanner(registry, maxSplits);
        QueryRequest req = new QueryRequest(
            "v1",
            UUID.randomUUID(),
            1,
            "t-lab",
            "lab",
            dbName,
            sql,
            (Option) snapshotOpt,
            new QueryLimits(10000, 30000L, maxSplits, 2, 2097152L)
        );
        PhysicalQuery pq = sqlPlanner.plan(req).right().get();
        Option compiledPred = Option.empty();
        if (pq.filter().isDefined()) {
            Table tbl = registry.table(pq.table()).right().get();
            scala.util.Either predEither = new PredicateCompiler().compile(
                (org.apache.calcite.rex.RexNode) pq.filter().get(),
                tbl.rowType(),
                pq.requiredSourceFields()
            );
            compiledPred = Option.apply(predEither.right().get());
        }
        return (PlannedScan) scanPlanner.plan(pq, compiledPred, maxSplits).right().get();
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static List<scala.collection.immutable.Vector<Object>> executePlannedScan(
            ActorSystem system,
            PlannedScan scan) throws Exception {
        scala.util.Either sourceEither = PaimonSplitSource.create(scan, 2);
        org.apache.pekko.stream.scaladsl.Source<scala.collection.immutable.Vector<Object>, ?> src =
            (org.apache.pekko.stream.scaladsl.Source<scala.collection.immutable.Vector<Object>, ?>) sourceEither.right().get();
        Materializer mat = SystemMaterializer.get(system).materializer();
        scala.collection.immutable.Seq<scala.collection.immutable.Vector<Object>> seq =
            Await.result(src.runWith(Sink.seq(), mat), Duration.create(30, TimeUnit.SECONDS));
        return JavaConverters.seqAsJavaList(seq);
    }

    public static void main(String[] args) throws Exception {
        Properties env = loadEnv(args[0]);
        String outDir = args[1];
        Files.createDirectories(Paths.get(outDir));

        String jdbcWarehouse = "s3://warehouse/paimon-storage-kernel";
        String catalogKey = "lab-storage-kernel";
        String dbName = "lab_storage_kernel_p35";

        Map<String, String> jdbcMap = jdbcCatalogProps(env, jdbcWarehouse, catalogKey);

        ActorSystem system = ActorSystem.create(
            "paimon-kernel-lab-p35",
            ConfigFactory.parseString(
                "pekko-query-server.blocking-dispatcher {\n" +
                "  type = Dispatcher\n" +
                "  executor = \"thread-pool-executor\"\n" +
                "  thread-pool-executor { fixed-pool-size = 4 }\n" +
                "  throughput = 1\n" +
                "}\n"
            ).withFallback(ConfigFactory.load())
        );

        StringBuilder report = new StringBuilder();
        report.append("=== PAIMON 1.2.0 x RUSTFS 1.0.0 x PEKKO QUERY SERVER: PART 3, 4 & 5 EVIDENCE ===\n");

        java.nio.file.Path localTmp = Files.createTempDirectory("paimon-p35-iomgr-");

        try (Catalog jdbcCatalog = CatalogFactory.createCatalog(CatalogContext.create(Options.fromMap(jdbcMap)));
             IOManager ioManager = IOManager.create(localTmp.toString())) {

            try {
                for (String tbl : jdbcCatalog.listTables(dbName)) {
                    jdbcCatalog.dropTable(Identifier.create(dbName, tbl), true);
                }
                jdbcCatalog.dropDatabase(dbName, true, true);
            } catch (Exception ignored) {}
            FileIO rootFio = FileIO.get(new Path(jdbcWarehouse), CatalogContext.create(Options.fromMap(jdbcMap)));
            try { rootFio.delete(new Path(jdbcWarehouse + "/" + dbName + ".db"), true); } catch (Exception ignored) {}
            jdbcCatalog.createDatabase(dbName, true);

            scala.collection.immutable.Map<String, String> scalaJdbcOpts =
                scala.collection.immutable.Map$.MODULE$.from(JavaConverters.mapAsScalaMapConverter(jdbcMap).asScala());
            CatalogSettings cs = new CatalogSettings("lab", "jdbc", jdbcWarehouse, scalaJdbcOpts);
            CatalogRegistry registry = CatalogRegistry.create(
                JavaConverters.asScalaBufferConverter(Collections.singletonList(cs)).asScala().toSeq()
            ).right().get();

            // =========================================================================
            // EXPERIMENT 3A: Changelog Producer none vs input vs lookup on RustFS
            // =========================================================================
            report.append("\n[EXP-3A] Changelog Producer (none vs input vs lookup) on RustFS:\n");
            for (String producer : Arrays.asList("none", "input", "lookup")) {
                Identifier id = Identifier.create(dbName, "orders_chg_" + producer);
                Schema sch = Schema.newBuilder()
                    .column("dt", DataTypes.STRING())
                    .column("order_id", DataTypes.BIGINT())
                    .column("user_id", DataTypes.BIGINT())
                    .column("amount", DataTypes.BIGINT())
                    .column("status", DataTypes.STRING())
                    .partitionKeys("dt")
                    .primaryKey("dt", "order_id")
                    .option("bucket", "1")
                    .option("changelog-producer", producer)
                    .build();
                jdbcCatalog.createTable(id, sch, false);
                FileStoreTable tbl = (FileStoreTable) jdbcCatalog.getTable(id);

                String user = "chg-" + producer;
                StreamTableWrite w = (StreamTableWrite) tbl.newStreamWriteBuilder().withCommitUser(user).newWrite().withIOManager(ioManager);
                StreamTableCommit c = tbl.newStreamWriteBuilder().withCommitUser(user).newCommit();
                boolean waitComp = "lookup".equals(producer);

                // Commit 1: INSERT id=1 (100, CREATED), id=2 (200, CREATED)
                w.write(orderRow(RowKind.INSERT, "2026-12-05", 1L, 10L, 100L, "CREATED"));
                w.write(orderRow(RowKind.INSERT, "2026-12-05", 2L, 20L, 200L, "CREATED"));
                if (waitComp) w.compact(partRow("2026-12-05"), 0, true);
                c.commit(1L, w.prepareCommit(waitComp, 1L));

                // Commit 2: Upsert +U ONLY (no -U provided by upstream!):
                // id=1 changes 100->150, PAID; id=2 repeats identical (200, CREATED)
                w.write(orderRow(RowKind.UPDATE_AFTER, "2026-12-05", 1L, 10L, 150L, "PAID"));
                w.write(orderRow(RowKind.UPDATE_AFTER, "2026-12-05", 2L, 20L, 200L, "CREATED"));
                if (waitComp) w.compact(partRow("2026-12-05"), 0, false);
                c.commit(2L, w.prepareCommit(waitComp, 2L));
                w.close();
                c.close();

                Snapshot latest = tbl.snapshotManager().latestSnapshot();
                List<String> changelogObjects = new ArrayList<>();
                for (String obj : listAllObjects(tbl.fileIO(), tbl.location())) {
                    if (obj.contains("changelog-")) changelogObjects.add(obj);
                }

                // Read incremental stream changes starting after snapshot 1
                FileStoreTable streamTbl = tbl.copy(Collections.singletonMap("scan.snapshot-id", "2"));
                ReadBuilder rb = streamTbl.newReadBuilder();
                StreamTableScan streamScan = rb.newStreamScan();
                // Restore cursor to snapshot 2 so it reads changes produced from snapshot 2 onward
                streamScan.restore(2L);
                List<String> streamEvents = new ArrayList<>();
                while (true) {
                    List<Split> splits = streamScan.plan().splits();
                    if (splits.isEmpty()) break;
                    try (RecordReader<InternalRow> reader = rb.newRead().createReader(splits)) {
                        RecordReader.RecordIterator<InternalRow> batch;
                        while ((batch = reader.readBatch()) != null) {
                            InternalRow row;
                            while ((row = batch.next()) != null) {
                                streamEvents.add(row.getRowKind().shortString() + "(id=" + row.getLong(1) +
                                    ",amt=" + row.getLong(3) + ",st=" + row.getString(4) + ")");
                            }
                            batch.releaseBatch();
                        }
                    }
                }

                List<scala.collection.immutable.Vector<Object>> batchRows = executePlannedScan(
                    system,
                    planViaPekkoServer(registry, dbName, "SELECT order_id, amount, status FROM orders_chg_" + producer + " LIMIT 100", Option.empty(), 32)
                );

                report.append("  * producer=").append(producer)
                      .append(" | latestSnap=").append(latest.id())
                      .append(" | changelogManifestList=").append(latest.changelogManifestList() != null)
                      .append(" | rustfsChangelogFiles=").append(changelogObjects.size())
                      .append("\n    - Incremental stream events from snap>=2: ").append(streamEvents)
                      .append("\n    - Pekko batch snapshot rows: ").append(batchRows.size()).append("\n");
            }

            // =========================================================================
            // EXPERIMENT 3B: partial-update Out-of-Order Replay (no sequence.field vs sequence.field)
            // =========================================================================
            report.append("\n[EXP-3B] partial-update Out-of-Order Replay (without vs with sequence.field):\n");
            for (boolean withSeq : Arrays.asList(false, true)) {
                String tName = withSeq ? "orders_partial_seq" : "orders_partial_noseq";
                Identifier id = Identifier.create(dbName, tName);
                Schema.Builder sb = Schema.newBuilder()
                    .column("dt", DataTypes.STRING())
                    .column("order_id", DataTypes.BIGINT())
                    .column("pay_amount", DataTypes.BIGINT())
                    .column("ship_status", DataTypes.STRING())
                    .column("event_ver", DataTypes.BIGINT())
                    .partitionKeys("dt")
                    .primaryKey("dt", "order_id")
                    .option("bucket", "1")
                    .option("merge-engine", "partial-update");
                if (withSeq) sb.option("sequence.field", "event_ver");
                jdbcCatalog.createTable(id, sb.build(), false);
                FileStoreTable tbl = (FileStoreTable) jdbcCatalog.getTable(id);

                StreamTableWrite w = tbl.newStreamWriteBuilder().newWrite();
                StreamTableCommit c = tbl.newStreamWriteBuilder().newCommit();
                // First arrives v2 (already SHIPPED, pay_amount null from logistics stream)
                w.write(GenericRow.ofKind(RowKind.INSERT, BinaryString.fromString("2026-12-05"), 10L, 500L, BinaryString.fromString("SHIPPED"), 2L));
                c.commit(1L, w.prepareCommit(false, 1L));
                // Then delayed/replayed v1 arrives from payment retry carrying stale ship_status="PENDING"
                w.write(GenericRow.ofKind(RowKind.UPDATE_AFTER, BinaryString.fromString("2026-12-05"), 10L, 500L, BinaryString.fromString("PENDING"), 1L));
                c.commit(2L, w.prepareCommit(false, 2L));
                w.close();
                c.close();

                List<scala.collection.immutable.Vector<Object>> res = executePlannedScan(
                    system,
                    planViaPekkoServer(registry, dbName, "SELECT order_id, pay_amount, ship_status, event_ver FROM " + tName + " LIMIT 10", Option.empty(), 16)
                );
                report.append("  * ").append(tName).append(" -> ").append(res).append("\n");
            }

            // =========================================================================
            // EXPERIMENT 4: FileStoreCommitImpl 4-Scenario OCC Matrix on JdbcCatalog + RustFS
            // =========================================================================
            report.append("\n[EXP-4] FileStoreCommitImpl 4-Scenario OCC Conflict Matrix on JdbcCatalog + RustFS:\n");

            // 4A: Concurrent L0 Append + L0 Append
            {
                Identifier id = Identifier.create(dbName, "occ_4a_append");
                jdbcCatalog.createTable(id, baseOccSchema(false), false);
                FileStoreTable tbl = (FileStoreTable) jdbcCatalog.getTable(id);
                StreamTableWrite wA = tbl.newStreamWriteBuilder().withCommitUser("uA").newWrite();
                StreamTableCommit cA = tbl.newStreamWriteBuilder().withCommitUser("uA").newCommit();
                StreamTableWrite wB = tbl.newStreamWriteBuilder().withCommitUser("uB").newWrite();
                StreamTableCommit cB = tbl.newStreamWriteBuilder().withCommitUser("uB").newCommit();

                wA.write(orderRow(RowKind.INSERT, "2026-12-05", 1L, 1L, 100L, "A"));
                List<CommitMessage> mA = wA.prepareCommit(false, 1L);
                wB.write(orderRow(RowKind.INSERT, "2026-12-05", 2L, 2L, 200L, "B"));
                List<CommitMessage> mB = wB.prepareCommit(false, 1L);

                cA.commit(1L, mA);
                cB.commit(1L, mB);
                wA.close(); cA.close(); wB.close(); cB.close();
                report.append("  * 4A (L0 Append || L0 Append): SUCCESS, latestSnap=")
                      .append(tbl.snapshotManager().latestSnapshotId()).append("\n");
            }

            // 4B: Stream L0 Append commits WHILE Standalone Full Compaction is in-flight
            {
                Identifier id = Identifier.create(dbName, "occ_4b_append_vs_compact");
                jdbcCatalog.createTable(id, baseOccSchema(false), false);
                FileStoreTable tbl = (FileStoreTable) jdbcCatalog.getTable(id);

                // Seed 3 L0 snapshots
                StreamTableWrite wSeed = tbl.newStreamWriteBuilder().withCommitUser("seed").newWrite();
                StreamTableCommit cSeed = tbl.newStreamWriteBuilder().withCommitUser("seed").newCommit();
                for (int i = 1; i <= 3; i++) {
                    wSeed.write(orderRow(RowKind.INSERT, "2026-12-05", i, i, i * 100L, "SEED"));
                    cSeed.commit(i, wSeed.prepareCommit(false, i));
                }
                wSeed.close(); cSeed.close();

                // Compactor prepares full compaction based on snapshot-3
                FileStoreTable compTbl = tbl.copy(Collections.singletonMap("write-only", "false"));
                StreamTableWrite wComp = (StreamTableWrite) compTbl.newStreamWriteBuilder().withCommitUser("compactor").newWrite().withIOManager(ioManager);
                StreamTableCommit cComp = compTbl.newStreamWriteBuilder().withCommitUser("compactor").newCommit();
                wComp.compact(partRow("2026-12-05"), 0, true);
                List<CommitMessage> compMsgs = wComp.prepareCommit(true, 10L);

                // Meanwhile Stream Writer commits snapshot-4 (new L0 file)
                StreamTableWrite wStream = tbl.newStreamWriteBuilder().withCommitUser("stream").newWrite();
                StreamTableCommit cStream = tbl.newStreamWriteBuilder().withCommitUser("stream").newCommit();
                wStream.write(orderRow(RowKind.INSERT, "2026-12-05", 4L, 4L, 400L, "STREAM_NEW"));
                cStream.commit(4L, wStream.prepareCommit(false, 4L));
                wStream.close(); cStream.close();

                // Now Compactor commits its snapshot-3-based compaction onto snapshot-4!
                cComp.commit(10L, compMsgs);
                wComp.close(); cComp.close();

                List<scala.collection.immutable.Vector<Object>> rows4b = executePlannedScan(
                    system,
                    planViaPekkoServer(registry, dbName, "SELECT order_id, amount FROM occ_4b_append_vs_compact LIMIT 20", Option.empty(), 16)
                );
                Snapshot s4 = tbl.snapshotManager().snapshot(4L);
                Snapshot s5 = tbl.snapshotManager().snapshot(5L);
                report.append("  * 4B (L0 Append snap-4 || Stale-Base Compaction rebase -> snap-5): SUCCESS, snap4.kind=")
                      .append(s4.commitKind()).append(", snap5.kind=").append(s5.commitKind())
                      .append(", survivingRows=").append(rows4b.size()).append("/4\n");
            }

            // 4C: Two Independent Compactors Picking Overlapping L0 Files -> Conflict!
            {
                Identifier id = Identifier.create(dbName, "occ_4c_double_compact");
                jdbcCatalog.createTable(id, baseOccSchema(false), false);
                FileStoreTable tbl = (FileStoreTable) jdbcCatalog.getTable(id);

                StreamTableWrite wSeed = tbl.newStreamWriteBuilder().withCommitUser("seed").newWrite();
                StreamTableCommit cSeed = tbl.newStreamWriteBuilder().withCommitUser("seed").newCommit();
                for (int i = 1; i <= 3; i++) {
                    wSeed.write(orderRow(RowKind.INSERT, "2026-12-05", i, i, i * 100L, "SEED"));
                    cSeed.commit(i, wSeed.prepareCommit(false, i));
                }
                wSeed.close(); cSeed.close();

                FileStoreTable compTbl = tbl.copy(Collections.singletonMap("write-only", "false"));
                StreamTableWrite wC1 = (StreamTableWrite) compTbl.newStreamWriteBuilder().withCommitUser("comp1").newWrite().withIOManager(ioManager);
                StreamTableCommit cC1 = compTbl.newStreamWriteBuilder().withCommitUser("comp1").newCommit();
                StreamTableWrite wC2 = (StreamTableWrite) compTbl.newStreamWriteBuilder().withCommitUser("comp2").newWrite().withIOManager(ioManager);
                StreamTableCommit cC2 = compTbl.newStreamWriteBuilder().withCommitUser("comp2").newCommit();

                wC1.compact(partRow("2026-12-05"), 0, true);
                List<CommitMessage> m1 = wC1.prepareCommit(true, 1L);
                wC2.compact(partRow("2026-12-05"), 0, true);
                List<CommitMessage> m2 = wC2.prepareCommit(true, 1L);

                cC1.commit(1L, m1);
                String conflictErr = "NONE";
                try {
                    cC2.commit(1L, m2);
                } catch (Throwable t) {
                    conflictErr = t.getClass().getName() + ": " + firstLine(t.getMessage());
                }
                wC1.close(); cC1.close(); wC2.close(); cC2.close();
                report.append("  * 4C (Compactor-1 || Compactor-2 overlapping input files): REJECTED -> ")
                      .append(conflictErr).append("\n");
            }

            // 4D: Deletion Vectors Concurrent DV Index Update on Same Base File
            {
                Identifier id = Identifier.create(dbName, "occ_4d_dv_conflict");
                jdbcCatalog.createTable(id, baseOccSchema(true), false);
                FileStoreTable tbl = (FileStoreTable) jdbcCatalog.getTable(id);

                // Seed base L5 file with rows 1..10
                StreamTableWrite wSeed = (StreamTableWrite) tbl.newStreamWriteBuilder().withCommitUser("seed").newWrite().withIOManager(ioManager);
                StreamTableCommit cSeed = tbl.newStreamWriteBuilder().withCommitUser("seed").newCommit();
                for (int i = 1; i <= 10; i++) {
                    wSeed.write(orderRow(RowKind.INSERT, "2026-12-05", i, i, i * 100L, "BASE"));
                }
                wSeed.compact(partRow("2026-12-05"), 0, true);
                cSeed.commit(1L, wSeed.prepareCommit(true, 1L));
                wSeed.close(); cSeed.close();

                // Two writers concurrently update rows in the same L5 base file & produce DV index updates
                StreamTableWrite w1 = (StreamTableWrite) tbl.newStreamWriteBuilder().withCommitUser("dv1").newWrite().withIOManager(ioManager);
                StreamTableCommit c1 = tbl.newStreamWriteBuilder().withCommitUser("dv1").newCommit();
                StreamTableWrite w2 = (StreamTableWrite) tbl.newStreamWriteBuilder().withCommitUser("dv2").newWrite().withIOManager(ioManager);
                StreamTableCommit c2 = tbl.newStreamWriteBuilder().withCommitUser("dv2").newCommit();

                w1.write(orderRow(RowKind.UPDATE_AFTER, "2026-12-05", 1L, 1L, 999L, "DV1"));
                w1.compact(partRow("2026-12-05"), 0, false);
                List<CommitMessage> m1 = w1.prepareCommit(true, 2L);

                w2.write(orderRow(RowKind.UPDATE_AFTER, "2026-12-05", 2L, 2L, 888L, "DV2"));
                w2.compact(partRow("2026-12-05"), 0, false);
                List<CommitMessage> m2 = w2.prepareCommit(true, 2L);

                c1.commit(2L, m1);
                String dvOutcome = "COMMITTED";
                try {
                    c2.commit(2L, m2);
                } catch (Throwable t) {
                    dvOutcome = "REJECTED -> " + t.getClass().getName() + ": " + firstLine(t.getMessage());
                }
                w1.close(); c1.close(); w2.close(); c2.close();
                report.append("  * 4D (Concurrent DV index update on same L5 base file): ").append(dvOutcome).append("\n");
            }

            // =========================================================================
            // EXPERIMENT 5A & 5B: Mid-Query expire_snapshots, Consumer/Tag Pinning, and OrphanFilesClean
            // =========================================================================
            report.append("\n[EXP-5A] Slow Pekko Query vs expire_snapshots (Unprotected vs Consumer/Tag Protected):\n");
            {
                Identifier idUnprot = Identifier.create(dbName, "orders_expire_unprot");
                jdbcCatalog.createTable(idUnprot, baseOccSchema(false), false);
                FileStoreTable tblU = (FileStoreTable) jdbcCatalog.getTable(idUnprot);
                seedFiveCompactedSnapshots(tblU, ioManager);

                // Pekko Query Server plans scan pinned to snapshot-1 BEFORE expiration
                PlannedScan pinnedScanU = planViaPekkoServer(
                    registry, dbName, "SELECT order_id, amount FROM orders_expire_unprot LIMIT 50", Option.apply(1L), 16
                );

                // Maintenance expires snapshots down to retainMax=1
                int expiredCountU = tblU.newExpireSnapshots()
                    .config(ExpireConfig.builder().snapshotRetainMax(1).snapshotRetainMin(1).snapshotTimeRetain(java.time.Duration.ZERO).build())
                    .expire();

                // Now slow Pekko Query Server attempts to stream the planned splits of snapshot-1
                String readAfterExpireErr = "NONE";
                try {
                    executePlannedScan(system, pinnedScanU);
                } catch (Throwable t) {
                    readAfterExpireErr = t.getClass().getName() + ": " + firstLine(t.getMessage());
                }
                report.append("  * Unprotected snapshot-1: expiredCount=").append(expiredCountU)
                      .append(", snap1Exists=").append(tblU.snapshotManager().snapshotExists(1L))
                      .append(", Pekko late read outcome -> ").append(readAfterExpireErr).append("\n");

                // Now test Protected table with Consumer ID pinning snapshot-1
                Identifier idProt = Identifier.create(dbName, "orders_expire_protected");
                jdbcCatalog.createTable(idProt, baseOccSchema(false), false);
                FileStoreTable tblP = (FileStoreTable) jdbcCatalog.getTable(idProt);
                seedFiveCompactedSnapshots(tblP, ioManager);

                // Pin snapshot-1 with ConsumerManager (nextSnapshot = 1L) AND create tag on snapshot-2
                ConsumerManager cm = new ConsumerManager(tblP.fileIO(), tblP.location());
                cm.resetConsumer("pekko-gateway-lease", new Consumer(1L));
                tblP.createTag("audit-tag-s2", 2L);

                PlannedScan pinnedScanP = planViaPekkoServer(
                    registry, dbName, "SELECT order_id, amount FROM orders_expire_protected LIMIT 50", Option.apply(1L), 16
                );
                int expiredCountP = tblP.newExpireSnapshots()
                    .config(ExpireConfig.builder().snapshotRetainMax(1).snapshotRetainMin(1).snapshotTimeRetain(java.time.Duration.ZERO).build())
                    .expire();
                List<scala.collection.immutable.Vector<Object>> protectedRows = executePlannedScan(system, pinnedScanP);

                // Release consumer lease, then re-run expire -> now snapshots 1..4 can expire, while tagged snapshot-2's data files stay readable via tag!
                cm.deleteConsumer("pekko-gateway-lease");
                int expiredAfterRelease = tblP.newExpireSnapshots()
                    .config(ExpireConfig.builder().snapshotRetainMax(1).snapshotRetainMin(1).snapshotTimeRetain(java.time.Duration.ZERO).build())
                    .expire();

                report.append("  * Consumer-pinned snapshot-1: expiredCountWhilePinned=").append(expiredCountP)
                      .append(", snap1Exists=").append(tblP.snapshotManager().snapshotExists(1L))
                      .append(", Pekko late read rows=").append(protectedRows.size())
                      .append(", expiredCountAfterConsumerRelease=").append(expiredAfterRelease)
                      .append(", tagExists(audit-tag-s2)=").append(tblP.tagManager().tagExists("audit-tag-s2"))
                      .append("\n");
            }

            report.append("\n[EXP-5B] Crash Orphan Files vs In-Flight Uncommitted Files (LocalOrphanFilesClean Safety Window):\n");
            {
                Identifier idOrphan = Identifier.create(dbName, "orders_orphan_clean");
                jdbcCatalog.createTable(idOrphan, baseOccSchema(false), false);
                FileStoreTable tblO = (FileStoreTable) jdbcCatalog.getTable(idOrphan);

                // 1) Simulate crashed writer leaving an uncommitted Parquet file on RustFS
                StreamTableWrite wCrashed = tblO.newStreamWriteBuilder().withCommitUser("crashed-pod").newWrite();
                wCrashed.write(orderRow(RowKind.INSERT, "2026-12-05", 901L, 9L, 900L, "ORPHAN"));
                List<CommitMessage> leakedMsgs = wCrashed.prepareCommit(false, 1L);
                wCrashed.close(); // Pod killed before commit!

                Thread.sleep(2200L);
                long cutoffBetweenCrashAndInFlight = System.currentTimeMillis() - 700L;

                // 2) Simulate active in-flight writer that JUST uploaded its Parquet file (< 700ms ago) and hasn't committed yet
                StreamTableWrite wActive = tblO.newStreamWriteBuilder().withCommitUser("active-pod").newWrite();
                StreamTableCommit cActive = tblO.newStreamWriteBuilder().withCommitUser("active-pod").newCommit();
                wActive.write(orderRow(RowKind.INSERT, "2026-12-05", 101L, 1L, 100L, "LIVE_IN_FLIGHT"));
                List<CommitMessage> inFlightMsgs = wActive.prepareCommit(false, 1L);

                // 3) Run LocalOrphanFilesClean at cutoffBetweenCrashAndInFlight:
                // Must delete crashed-pod's stale orphan Parquet file, while sparing active-pod's in-flight Parquet file!
                LocalOrphanFilesClean cleaner = new LocalOrphanFilesClean(tblO, cutoffBetweenCrashAndInFlight, false);
                CleanOrphanFilesResult cleanRes = cleaner.clean();

                // 4) Active writer now commits its in-flight messages and Pekko Query Server reads the table!
                cActive.commit(1L, inFlightMsgs);
                wActive.close();
                cActive.close();

                List<scala.collection.immutable.Vector<Object>> liveRows = executePlannedScan(
                    system,
                    planViaPekkoServer(registry, dbName, "SELECT order_id, status FROM orders_orphan_clean LIMIT 20", Option.empty(), 16)
                );

                report.append("  * Orphan clean deletedFileCount=").append(cleanRes.getDeletedFileCount())
                      .append(", deletedBytes=").append(cleanRes.getDeletedFileTotalLenInBytes())
                      .append(", deletedPaths=").append(cleanRes.getDeletedFilesPath())
                      .append("\n  * In-flight writer commit after clean: SUCCESS, Pekko verified rows=").append(liveRows).append("\n");
            }

            registry.close();
        } finally {
            Await.result(system.terminate(), Duration.create(10, TimeUnit.SECONDS));
        }

        String resultText = report.toString();
        System.out.println(resultText);
        Files.write(Paths.get(outDir, "part3-5-results.txt"), resultText.getBytes(StandardCharsets.UTF_8));
    }

    private static Schema baseOccSchema(boolean dv) {
        Schema.Builder b = Schema.newBuilder()
            .column("dt", DataTypes.STRING())
            .column("order_id", DataTypes.BIGINT())
            .column("user_id", DataTypes.BIGINT())
            .column("amount", DataTypes.BIGINT())
            .column("status", DataTypes.STRING())
            .partitionKeys("dt")
            .primaryKey("dt", "order_id")
            .option("bucket", "1");
        if (dv) {
            b.option("deletion-vectors.enabled", "true");
        } else {
            b.option("write-only", "true");
        }
        return b.build();
    }

    private static void seedFiveCompactedSnapshots(FileStoreTable tbl, IOManager ioManager) throws Exception {
        FileStoreTable compTbl = tbl.copy(Collections.singletonMap("write-only", "false"));
        StreamTableWrite w = (StreamTableWrite) compTbl.newStreamWriteBuilder().withCommitUser("seed5").newWrite().withIOManager(ioManager);
        StreamTableCommit c = compTbl.newStreamWriteBuilder().withCommitUser("seed5").newCommit();
        for (int s = 1; s <= 5; s++) {
            w.write(orderRow(RowKind.UPDATE_AFTER, "2026-12-05", 1L, 1L, s * 100L, "V" + s));
            w.write(orderRow(RowKind.INSERT, "2026-12-05", s + 10L, 1L, s * 10L, "S" + s));
            w.compact(partRow("2026-12-05"), 0, true);
            c.commit(s, w.prepareCommit(true, s));
        }
        w.close();
        c.close();
    }

    private static String firstLine(String msg) {
        if (msg == null) return "";
        int nl = msg.indexOf('\n');
        return nl >= 0 ? msg.substring(0, nl) : msg;
    }
}
