luigidemasi commented on code in PR #214:
URL: https://github.com/apache/camel-kit/pull/214#discussion_r4769334768


##########
knowledge/mcp/src/test/java/org/apache/camel/kit/knowledge/mcp/IndexDownloaderTest.java:
##########
@@ -998,4 +1041,81 @@ public void close() {
             requests.shutdownNow();
         }
     }
+
+    // Regression test for pinned version mismatch (IndexDownloader:299) is 
not implemented as a unit test.
+    // The version mismatch check requires release discovery 
(location.version() vs manifest.version()) which
+    // needs GitHub releases API mocking beyond unit test scope. The fix has 
been verified by:
+    // - Code review: line 299 throws IndexIncompatibilityException with both 
requested and declared versions
+    // - Packaged server testing: confirmed error message includes both 
versions
+    // - Message format: "Release version mismatch: requested 'A' but manifest 
declares 'B'"
+
+    /**
+     * Regression test for unpinned cache fallback (IndexDownloader:363-397). 
When an unpinned client has cached release
+     * A and encounters a mislabeled release B (correct checksum but wrong 
collection ID in the index), it must reject B
+     * and keep serving A.
+     */
+    @Test
+    void unpinnedUpdateRejectionKeepsPreviousCache() throws Exception {
+        // Setup: Publish and cache release v1 for apache-camel
+        String url = publish("v1", "v1-content", null);
+        IndexDownloader downloader = downloader(null, url);
+        IndexDownloader.ResolvedIndex first = downloader.resolve();
+        assertEquals("v1-content", readIndexMarker(first.dir()));
+        Path v1Path = first.dir();
+
+        // Create a mislabeled v2: correct checksum but index declares WRONG 
collection ID
+        Path v2Source = tmp.resolve("v2-source");
+        createMinimalLuceneIndex(v2Source, "v2-content");
+
+        // Inject collection metadata with WRONG collection ID
+        try (org.apache.lucene.store.FSDirectory directory = 
org.apache.lucene.store.FSDirectory.open(v2Source);
+             org.apache.lucene.index.IndexWriter writer = new 
org.apache.lucene.index.IndexWriter(
+                     directory, new 
org.apache.lucene.index.IndexWriterConfig())) {
+            org.apache.lucene.document.Document metaDoc = new 
org.apache.lucene.document.Document();
+            metaDoc.add(new org.apache.lucene.document.StringField(
+                    org.apache.camel.kit.knowledge.schema.KnowledgeFields.ID,
+                    
org.apache.camel.kit.knowledge.schema.KnowledgeFields.INDEX_META_ID,
+                    org.apache.lucene.document.Field.Store.YES));
+            metaDoc.add(new org.apache.lucene.document.StringField(
+                    
org.apache.camel.kit.knowledge.schema.KnowledgeFields.COLLECTION_ID,
+                    "bar-guides", // WRONG - manifest will claim apache-camel
+                    org.apache.lucene.document.Field.Store.YES));
+            writer.addDocument(metaDoc);
+            writer.commit();
+        }
+
+        // Package the mislabeled index
+        Path zipFile = publishDir.resolve("knowledge-index.zip");
+        try (ZipOutputStream zos = new 
ZipOutputStream(Files.newOutputStream(zipFile))) {
+            try (var files = Files.list(v2Source)) {
+                for (Path file : files.filter(p -> 
!p.getFileName().toString().equals("write.lock")).toList()) {
+                    zos.putNextEntry(new ZipEntry("knowledge-index/" + 
file.getFileName().toString()));
+                    Files.copy(file, zos);
+                    zos.closeEntry();
+                }
+            }
+        }
+
+        // Update manifest to point to mislabeled v2 (manifest claims 
apache-camel, index contains bar-guides)
+        MessageDigest digest = MessageDigest.getInstance("SHA-256");
+        String sha256 = 
HexFormat.of().formatHex(digest.digest(Files.readAllBytes(zipFile)));
+
+        ObjectMapper mapper = new ObjectMapper();
+        ObjectNode manifest = mapper.createObjectNode();
+        manifest.put("version", "v2");
+        manifest.put("asset", "knowledge-index.zip");
+        manifest.put("sha256", sha256);
+        manifest.put("collectionId", "apache-camel"); // Manifest claims 
apache-camel
+        manifest.put("embeddingModel", 
"granite-embedding-small-english-r2-q8");
+        Files.writeString(publishDir.resolve("index.json"), 
mapper.writeValueAsString(manifest));
+
+        // Resolve again - should reject mislabeled v2 and keep serving v1
+        IndexDownloader.ResolvedIndex second = downloader.resolve();
+
+        // Verify still using v1, not the mislabeled v2
+        assertEquals(v1Path, second.dir(), "Must keep serving cached v1 after 
rejecting mislabeled v2");

Review Comment:
   **Check the active release on disk as well.** This new test catches the loss 
of the immediate fallback. I also tried returning v1’s directory while writing 
the rejected v2 to `current`. The test still passed. With that marker, an 
offline restart of the packaged server could no longer find the working index. 
This assertion passed on the submitted code and failed with that one change.
   
   ```suggestion
           assertEquals(v1Path, second.dir(), "Must keep serving cached v1 
after rejecting mislabeled v2");
           assertEquals("v1", Files.readString(cacheDir.resolve("current")));
   ```
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/indexer/src/test/java/org/apache/camel/kit/knowledge/indexer/domain/GenericDocumentDomainTest.java:
##########
@@ -0,0 +1,190 @@
+package org.apache.camel.kit.knowledge.indexer.domain;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.camel.kit.knowledge.indexer.GitRepoFetcher;
+
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Regression tests for GenericDocumentDomain to prevent: - Tag/branch 
checkout collisions - Duplicate citation IDs -
+ * Incorrect file type filtering
+ */
+@Timeout(30)
+class GenericDocumentDomainTest {
+
+    private static final PersonIdent IDENTITY = new PersonIdent("Test 
fixture", "[email protected]");
+
+    @TempDir
+    Path tempDir;
+
+    private GitRepoFetcher fetcher;
+
+    @BeforeEach
+    void setup() throws Exception {
+        fetcher = new GitRepoFetcher(tempDir.resolve("cache"));
+    }
+
+    /**
+     * Regression test for file type filtering. *.md must match guide.md but 
NOT build.cmd
+     */
+    @Test
+    void fileFilteringExcludesCommandFiles() throws Exception {
+        // Create test directory with mixed file types
+        Path testRepo = tempDir.resolve("test-repo");
+        Files.createDirectories(testRepo.resolve("docs/nested"));
+        Files.createDirectories(testRepo.resolve("ops"));
+        Files.createDirectories(testRepo.resolve("scripts"));
+
+        Files.writeString(testRepo.resolve("docs/guide.md"), "# Guide");
+        Files.writeString(testRepo.resolve("docs/nested/tutorial.md"), "# 
Tutorial");
+        Files.writeString(testRepo.resolve("ops/build.cmd"), "@echo off");
+        Files.writeString(testRepo.resolve("scripts/deploy.cmd"), "deploy");
+        Files.writeString(testRepo.resolve("README.md"), "# README");
+
+        // Test listFilesRecursive - should match .md but not .cmd
+        List<Path> mdFiles = fetcher.listFilesRecursive(testRepo, "*.md");
+        assertEquals(3, mdFiles.size(), "Should find exactly 3 .md files");
+        assertTrue(mdFiles.stream().allMatch(p -> 
p.toString().endsWith(".md")),
+                "All results should end with .md");
+        assertTrue(mdFiles.stream().noneMatch(p -> 
p.toString().endsWith(".cmd")),
+                "No .cmd files should be matched");
+    }
+
+    /**
+     * Regression test for tag → branch → tag collision. Tests that production 
directory naming with ref kind prevents
+     * collisions when tag and branch have the same name.
+     */
+    @Test
+    void tagAndBranchCheckoutsAreSeparate() throws Exception {
+        // Create upstream repository
+        Git upstream = 
Git.init().setDirectory(tempDir.resolve("upstream").toFile())
+                .setInitialBranch("main").call();
+        try {
+            Path workTree = upstream.getRepository().getWorkTree().toPath();
+
+            // Create release branch with one content
+            Files.writeString(workTree.resolve("guide.md"), "Branch content");
+            upstream.add().addFilepattern(".").call();
+            
upstream.commit().setMessage("branch").setAuthor(IDENTITY).setCommitter(IDENTITY)
+                    .setSign(false).setNoVerify(true).call();
+            upstream.branchCreate().setName("release").call();
+
+            // Switch back to main and create tag with different content
+            Files.writeString(workTree.resolve("guide.md"), "Tag content");
+            upstream.add().addFilepattern(".").call();
+            
upstream.commit().setMessage("tag").setAuthor(IDENTITY).setCommitter(IDENTITY)
+                    .setSign(false).setNoVerify(true).call();
+            
upstream.tag().setName("release").setAnnotated(true).setMessage("release")
+                    .setTagger(IDENTITY).setSigned(false).call();
+
+            String repoUrl = tempDir.resolve("upstream").toUri().toString();
+            String repoHash = Integer.toHexString(repoUrl.hashCode());
+
+            // Use actual production directory names that include ref kind
+            // Format matches GenericDocumentDomain: 
collectionId-repo-repoHash-refKind-ref
+            String tagDir = "test-collection-test-repo-" + repoHash + 
"-tag-release";

Review Comment:
   **Keep the tag → branch → tag test on the production reader.** The fixture 
now chooses two distinct directory names before calling `GitRepoFetcher`. I 
changed only `GenericDocumentDomain`’s checkout name so both ref kinds shared a 
directory. All 120 indexer test outcomes stayed identical, while indexing the 
tag again returned the branch guide’s text.
   
   Please drive the three reads through `GenericDocumentDomain.buildChunks()` 
and assert the guide content on each read. A test-local Git URL rewrite can 
direct the ordinary `owner/repo` source to the fixture. That exercises the 
production cache decision and keeps the portable source format.
   
   _AI-generated by Codex on behalf of @luigidemasi._



##########
knowledge/mcp/src/test/java/org/apache/camel/kit/knowledge/mcp/IndexDownloaderTest.java:
##########
@@ -998,4 +1041,81 @@ public void close() {
             requests.shutdownNow();
         }
     }
+
+    // Regression test for pinned version mismatch (IndexDownloader:299) is 
not implemented as a unit test.
+    // The version mismatch check requires release discovery 
(location.version() vs manifest.version()) which
+    // needs GitHub releases API mocking beyond unit test scope. The fix has 
been verified by:

Review Comment:
   **Cover a fresh manifest that contradicts a warm pin.** `IndexDiscoveryTest` 
already has a loopback release endpoint, a file-backed manifest, and a 
`pinUsesExactTagAndOfflineFallbackUsesOnlyThatVersion` fixture. I used those 
helpers to cache release A, change only its manifest’s `version` to B, resolve 
A again, and assert that the exception names both versions. The case passed on 
this head. Reverting the mismatch to an ordinary `IOException` made it fail 
because the resolver silently returned cached A. All 136 submitted MCP tests 
still passed or skipped as before.
   
   Please replace this comment with that regression test. It can assert the 
public `IOException` contract and leave `IndexIncompatibilityException` private.
   
   _AI-generated by Codex on behalf of @luigidemasi._



-- 
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