Copilot commented on code in PR #7407:
URL: https://github.com/apache/paimon/pull/7407#discussion_r2919158366


##########
paimon-common/src/main/java/org/apache/paimon/lookup/sort/db/SimpleLsmKvDb.java:
##########
@@ -0,0 +1,582 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.lookup.sort.db;
+
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.compression.CompressOptions;
+import org.apache.paimon.io.cache.CacheManager;
+import org.apache.paimon.lookup.sort.SortLookupStoreFactory;
+import org.apache.paimon.lookup.sort.SortLookupStoreReader;
+import org.apache.paimon.lookup.sort.SortLookupStoreWriter;
+import org.apache.paimon.memory.MemorySlice;
+import org.apache.paimon.options.MemorySize;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * A simple LSM-Tree based KV database built on top of {@link 
SortLookupStoreFactory}.
+ *
+ * <p>Architecture (Universal Compaction, inspired by RocksDB):
+ *
+ * <pre>
+ *     ┌──────────────────────────────────────────────┐
+ *     │            MemTable (SkipList)                │  ← Active writes
+ *     ├──────────────────────────────────────────────┤
+ *     │  Sorted Runs (newest → oldest):              │
+ *     │    [Run-0] [Run-1] [Run-2] ... [Run-N]       │  ← Each run is a 
sorted SST file set
+ *     └──────────────────────────────────────────────┘
+ * </pre>
+ *
+ * <p>Compaction is triggered when the number of sorted runs exceeds a 
threshold. Runs are selected
+ * for merging based on size ratios between adjacent runs, following RocksDB's 
Universal Compaction
+ * strategy.
+ *
+ * <p>Note: No WAL is implemented. Data in the MemTable will be lost on crash.
+ *
+ * <p>This class is <b>not</b> thread-safe. External synchronization is 
required if accessed from
+ * multiple threads.
+ */
+public class SimpleLsmKvDb implements Closeable {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SimpleLsmKvDb.class);
+
+    /** Tombstone marker for deleted keys. */
+    private static final byte[] TOMBSTONE = new byte[0];
+
+    /** Maximum number of levels in the LSM tree. */
+    static final int MAX_LEVELS = 4;
+
+    /**
+     * Estimated per-entry memory overhead in the MemTable's TreeMap, beyond 
the raw key/value
+     * bytes. This accounts for:
+     *
+     * <ul>
+     *   <li>TreeMap.Entry node: ~64 bytes (object header + 
left/right/parent/key/value refs +
+     *       color)
+     *   <li>MemorySlice wrapper: ~32 bytes (object header + segment ref + 
offset + length)
+     *   <li>MemorySegment backing the key: ~48 bytes (object header + 
heapMemory/offHeapBuffer refs
+     *       + address + size)
+     *   <li>byte[] value array header: ~16 bytes (object header + length)
+     * </ul>
+     */
+    static final long PER_ENTRY_OVERHEAD = 160;
+
+    private final File dataDirectory;
+    private final SortLookupStoreFactory storeFactory;
+    private final Comparator<MemorySlice> keyComparator;
+    private final long memTableFlushThreshold;
+    private final LsmCompactor compactor;
+
+    /** Active MemTable: key -> value bytes (empty byte[] = tombstone). */
+    private TreeMap<MemorySlice, byte[]> memTable;
+
+    /** Estimated size of the current MemTable in bytes. */
+    private long memTableSize;
+
+    /**
+     * Multi-level SST file storage. Each level contains a list of {@link 
SstFileMetadata} ordered
+     * by key range. Level 0 files are ordered newest-first (key ranges may 
overlap). Level 1+ files
+     * are ordered by minKey (key ranges do NOT overlap).
+     */
+    private final List<List<SstFileMetadata>> levels;
+
+    /** Cached readers for SST files, keyed by file path. Lazily populated on 
first lookup. */
+    private final Map<File, SortLookupStoreReader> readerCache;
+
+    private long fileSequence;
+    private boolean closed;
+
+    private SimpleLsmKvDb(
+            File dataDirectory,
+            SortLookupStoreFactory storeFactory,
+            Comparator<MemorySlice> keyComparator,
+            long memTableFlushThreshold,
+            long maxSstFileSize,
+            int level0FileNumCompactTrigger,
+            int sizeRatio) {
+        this.dataDirectory = dataDirectory;
+        this.storeFactory = storeFactory;
+        this.keyComparator = keyComparator;
+        this.memTableFlushThreshold = memTableFlushThreshold;
+        this.memTable = new TreeMap<>(keyComparator);
+        this.memTableSize = 0;
+        this.levels = new ArrayList<>();
+        for (int i = 0; i < MAX_LEVELS; i++) {
+            this.levels.add(new ArrayList<>());
+        }
+        this.readerCache = new HashMap<>();
+        this.fileSequence = 0;
+        this.closed = false;
+        this.compactor =
+                new LsmCompactor(
+                        keyComparator,
+                        storeFactory,
+                        maxSstFileSize,
+                        level0FileNumCompactTrigger,
+                        sizeRatio,
+                        new LsmCompactor.FileDeleter() {
+                            @Override
+                            public void deleteFile(File file) {
+                                closeAndDeleteSstFile(file);
+                            }
+                        });
+    }
+
+    /**
+     * Close the cached reader for the given SST file (if any) and delete the 
file from disk. This
+     * is invoked by {@link LsmCompactor} via the {@link 
LsmCompactor.FileDeleter} callback during
+     * compaction.
+     */
+    private void closeAndDeleteSstFile(File file) {
+        SortLookupStoreReader reader = readerCache.remove(file);
+        if (reader != null) {
+            try {
+                reader.close();
+            } catch (IOException e) {
+                LOG.warn("Failed to close reader for SST file: {}", 
file.getName(), e);
+            }
+        }
+        if (file.exists()) {
+            boolean deleted = file.delete();
+            if (!deleted) {
+                LOG.warn("Failed to delete SST file: {}", file.getName());
+            }
+        }
+    }
+
+    // 
-------------------------------------------------------------------------
+    //  Builder
+    // 
-------------------------------------------------------------------------
+
+    /** Create a builder for {@link SimpleLsmKvDb}. */
+    public static Builder builder(File dataDirectory) {
+        return new Builder(dataDirectory);
+    }
+
+    // 
-------------------------------------------------------------------------
+    //  Write Operations
+    // 
-------------------------------------------------------------------------
+
+    /**
+     * Put a key-value pair into the database.
+     *
+     * @param key the key bytes, must not be null
+     * @param value the value bytes, must not be null
+     */
+    public void put(byte[] key, byte[] value) throws IOException {
+        ensureOpen();
+        MemorySlice wrappedKey = MemorySlice.wrap(key);
+        byte[] oldValue = memTable.put(wrappedKey, value);

Review Comment:
   `MemorySlice.wrap(key)` stores the caller-provided byte[] directly as the 
map key. If the caller mutates or reuses that array after `put/delete/get`, it 
can corrupt TreeMap ordering (and therefore reads/compactions) and also 
potentially retain mutable external data in-memory. Defensively copy `key` (and 
typically `value` as well) before storing/looking up (apply similarly in 
`delete` and `get`).
   ```suggestion
           // Defensively copy key and value to avoid external mutation 
affecting MemTable
           byte[] keyCopy = new byte[key.length];
           System.arraycopy(key, 0, keyCopy, 0, key.length);
           MemorySlice wrappedKey = MemorySlice.wrap(keyCopy);
           byte[] valueCopy = new byte[value.length];
           System.arraycopy(value, 0, valueCopy, 0, value.length);
           byte[] oldValue = memTable.put(wrappedKey, valueCopy);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to