From 252d9414d3f7b5071bd317b575473d923a2c6d20 Mon Sep 17 00:00:00 2001 From: Ajay Viswanathan Date: Sun, 19 Jul 2026 06:52:05 +0700 Subject: [PATCH 1/2] [feature] weights search ranking by resource view count Ranks search results by how often each resource is deliberately opened, so frequently consulted resources surface above equally relevant ones. UsageService counts views recorded by QueryService.describe -- opening a resource, never a search impression, which would boost whatever already ranked highly and is self-fulfilling. Counts live in cortex://usage, a reserved named graph beside cortex://provenance, so nothing here writes to the default graph and the review rule still holds. Views buffer in memory and flush in batches: TDB2 admits a single writer, so a write transaction per view would serialize the read path against ingestion. The Spring bean flushes on shutdown via destroyMethod. Only unflushed deltas are held in memory, never totals. Restore replaces the whole assertions dataset during context refresh, so a total cached at construction would be written back over the restored counts at the next flush -- silently, and only on replicas that restore. The current value is re-read inside the flush transaction, making the update a true increment. The weight saturates and is bounded at 2x. Raw counts would let one hot resource swamp textual relevance, and since boosted results are seen and so viewed more often, an unbounded weight compounds into a rich-get-richer loop that new resources cannot break into. Re-ranking runs over the whole candidate set rather than a truncated head, so a popular resource low in the candidates can still be promoted. UsageService is wired into QueryService rather than added as a role, so Cortex remains nine roles and JenaCortex eleven services. Both assembly paths construct it. Co-Authored-By: Claude Opus 4.8 --- CLAUDE.md | 30 ++- .../java/ai/chatur/cortex/CortexBuilder.java | 4 +- .../chatur/cortex/core/CortexNamespace.java | 12 ++ .../cortex/core/query/QueryService.java | 36 +++- .../cortex/core/usage/UsageService.java | 194 ++++++++++++++++++ .../ai/chatur/cortex/query/SearchTests.java | 45 ++++ .../cortex/usage/UsageServiceTests.java | 177 ++++++++++++++++ .../spring/CortexAutoConfiguration.java | 25 ++- 8 files changed, 515 insertions(+), 8 deletions(-) create mode 100644 cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java create mode 100644 cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java diff --git a/CLAUDE.md b/CLAUDE.md index fc8141f..05116e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,8 +45,8 @@ Spring's `Resource`. The Spring layer reads content as UTF-8 and passes strings `Resource` into core to save a line. `CortexBuilder` (`cortex-core`, package `ai.chatur.cortex`) assembles a `Cortex` without Spring and -wires the same eleven services `CortexAutoConfiguration` does. If you add a core service, **both** -need updating or the two assembly paths drift. +wires the same eleven services `CortexAutoConfiguration` does, plus `UsageService`. If you add a core +service, **both** need updating or the two assembly paths drift. The autoconfigure split is core / web / mcp / backup / restore (see `AutoConfiguration.imports`), grouped by how the graph is *delivered* — to the process, to humans, to agents, to durable storage, @@ -184,6 +184,26 @@ on both its label and its comment produces two Lucene documents and therefore tw so first is best. The raw-text `search(String)` variant is deliberately *not* de-duplicated — it reports the index verbatim. +**Search ranking is weighted by view count, and the write path is batched on purpose.** +`UsageService` counts *deliberate* views — `QueryService.describe`, i.e. someone opening a resource — +never search impressions, which would boost whatever already ranked highly and is self-fulfilling. +Counts live in `cortex://usage`, a reserved named graph beside `cortex://provenance`, so this is not a +write to the default graph and the review rule still holds. **Never write a count per view:** TDB2 is +single-writer, so that serializes the read path against ingestion. Views buffer in memory and flush in +batches; the Spring bean flushes on shutdown via `destroyMethod`. + +**`UsageService` holds only unflushed deltas, never totals.** Restore replaces the whole assertions +dataset during context refresh, so a total cached at construction would be written back over the +restored counts at the next flush. The current value is re-read *inside* the flush transaction, +making the update a true increment; `UsageServiceTests` pins this. Don't "optimize" it into a cached +map — the bug it reintroduces is silent and only shows up on restored replicas. + +**The popularity weight is bounded and saturating** (`1 + count/(count+5)`, capped at 2×). Raw counts +would let one hot resource swamp textual relevance, and since boosted results get viewed more, an +unbounded weight compounds into a rich-get-richer loop new resources cannot break into. Re-ranking +happens over the whole candidate set, not a truncated head — truncating first means a popular +resource low in the candidates can never be promoted, which defeats the point. + **`rdf:type` is deliberately not indexed.** It was, into the same field as `rdfs:label`, which mixed class-URI tokens into the same relevance space as human-readable prose and gave every typed resource the same filler terms. @@ -255,5 +275,11 @@ has nothing to restore; every other failure propagates and fails the boot. upload is a copy, not a move, deliberately: deleting the local file on a successful upload would make a bucket misconfiguration destructive. This is the `.cortex/` residue problem below, now with a scheduler behind it. Retention belongs to the volume, or to an S3 lifecycle rule. +- View counts have **no time decay**: a resource popular a year ago still outranks a newer one + forever. The bound keeps this from being severe, but recency weighting is the natural next step. + Counts also never expire for deleted resources — a rejected or removed subject keeps its row in + `cortex://usage`. +- Counts are lost under the default `cortex.persistent=false`, since the assertions dataset is then + in-memory. That matches the text index and the inference closure, and is a non-issue in production. - ~335 MB of gitignored `.cortex/` runtime residue sits in the tree (repo root and the example) from prior runs with persistence on. Safe to delete when no process holds `db/tdb.lock`. diff --git a/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java b/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java index c531066..b27fb31 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java @@ -18,6 +18,7 @@ import ai.chatur.cortex.core.stats.StatsService; import ai.chatur.cortex.core.store.AssertionStore; import ai.chatur.cortex.core.store.TextIndexFactory; +import ai.chatur.cortex.core.usage.UsageService; import java.util.List; import org.apache.jena.ontapi.model.OntModel; import org.apache.jena.query.Dataset; @@ -139,7 +140,8 @@ public Cortex build() { new BranchMergeService(assertions, branchRepository, provenanceRecorder); ArchiveService archiveService = new ArchiveService(assertions); InferenceService inferenceService = new InferenceService(assertions, inferences, reasoner); - QueryService queryService = new QueryService(inferences, assertions, ontModel); + UsageService usageService = new UsageService(assertions); + QueryService queryService = new QueryService(inferences, assertions, ontModel, usageService); StatsService statsService = new StatsService(assertions, inferences, ontModel, parsedShapes, parsedRules); diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java b/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java index 5ceadc0..9812d90 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java @@ -1,6 +1,7 @@ package ai.chatur.cortex.core; import java.util.UUID; +import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; @@ -13,6 +14,17 @@ public final class CortexNamespace { /** The named graph holding per-statement provenance within the assertions dataset. */ public static final Resource PROVENANCE = ResourceFactory.createResource(NS + "provenance"); + /** + * The named graph holding per-resource view counts within the assertions dataset. + * + *

Like {@link #PROVENANCE} this is a reserved graph, not a branch and not part of the approved + * assertions: it records how the graph is used rather than what it claims. + */ + public static final Resource USAGE = ResourceFactory.createResource(NS + "usage"); + + /** The property recording how many times a resource has been viewed, within {@link #USAGE}. */ + public static final Property VIEW_COUNT = ResourceFactory.createProperty(NS + "viewCount"); + private CortexNamespace() {} /** diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java b/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java index d430672..5d6fde8 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java @@ -8,9 +8,11 @@ import ai.chatur.cortex.core.jena.Rdf; import ai.chatur.cortex.core.jena.Sparql; import ai.chatur.cortex.core.store.TextIndexFactory; +import ai.chatur.cortex.core.usage.UsageService; import java.io.IOException; import java.io.UncheckedIOException; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -98,6 +100,7 @@ ORDER BY DESC(?score) private final Dataset inferences; private final Dataset assertions; private final OntModel ontModel; + private final UsageService usageService; /** * Creates the service. @@ -105,11 +108,14 @@ ORDER BY DESC(?score) * @param inferences the dataset holding the assertions enriched by inference * @param assertions the dataset holding the approved assertions and their provenance * @param ontModel the ontology model, used to resolve classes and shorten URIs + * @param usageService view counts, which weight the ranking of search results */ - public QueryService(Dataset inferences, Dataset assertions, OntModel ontModel) { + public QueryService( + Dataset inferences, Dataset assertions, OntModel ontModel, UsageService usageService) { this.inferences = inferences; this.assertions = assertions; this.ontModel = ontModel; + this.usageService = usageService; } /** @@ -184,6 +190,9 @@ List listInstances(OntClass ontClass) { * @return the statements about the resource, sorted by predicate */ public List describe(String id) { + // opening a resource is the deliberate-view signal that weights search ranking; recorded before + // the reads below because a flush needs its own write transaction and must not nest + usageService.recordView(id); Resource subject = ResourceFactory.createResource(id); Map created = getCreated(subject); List statements = new ArrayList<>(); @@ -297,7 +306,30 @@ public List searchSubjects(String text) { : 0)); } }); - return List.copyOf(best.values()); + return rankByPopularity(best); + } + + /** + * Weights each candidate by how often it has been viewed and re-sorts. + * + *

Re-ranking happens over the whole candidate set rather than a truncated head: a resource + * that text relevance alone placed near the bottom of the candidates can still be promoted, which + * is the entire point. The weight is bounded, so popularity reorders results of comparable + * textual relevance instead of overriding relevance outright. + * + * @param best the best-scoring hit per subject URI, in descending textual relevance + * @return the hits ranked by weighted relevance, best first + */ + private List rankByPopularity(Map best) { + Map weights = usageService.weights(best.keySet()); + return best.entrySet().stream() + .map(entry -> weighted(entry.getValue(), weights.getOrDefault(entry.getKey(), 1.0))) + .sorted(Comparator.comparingDouble(SearchResult::score).reversed()) + .toList(); + } + + private static SearchResult weighted(SearchResult result, double weight) { + return new SearchResult(result.subject(), result.match(), result.score() * weight); } /** diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java b/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java new file mode 100644 index 0000000..c74a05b --- /dev/null +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java @@ -0,0 +1,194 @@ +package ai.chatur.cortex.core.usage; + +import ai.chatur.cortex.core.CortexNamespace; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.jena.query.Dataset; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.ResourceFactory; +import org.apache.jena.rdf.model.Statement; +import org.apache.jena.system.Txn; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Counts how often each resource is deliberately viewed, and turns those counts into a search + * ranking weight. + * + *

Only deliberate views are counted — opening a resource, not merely appearing in a result list. + * Counting search impressions would boost whatever already ranked highly, which is self-fulfilling + * and accelerates the feedback loop described below. + * + *

Counts live in the {@link CortexNamespace#USAGE usage graph} of the assertions dataset, a + * reserved named graph alongside provenance. Writing there does not touch the default graph, so the + * rule that approved assertions are only ever reached through review still holds. + * + *

Views are not written as they happen. TDB2 admits a single writer, so a write + * transaction per view would serialize the read path against ingestion. Views accumulate in memory + * and are flushed in batches; a crash loses at most {@link #FLUSH_THRESHOLD} views, which is + * immaterial for a relevance signal. + * + *

Only the unflushed deltas are held in memory — never the totals. A restore replaces the whole + * assertions dataset partway through startup, and a cached total captured before that would be + * written back over the restored counts on the next flush. Reading the current value inside the + * flush transaction makes the update a true increment and sidesteps the ordering entirely. + */ +public class UsageService { + + private static final Logger log = LoggerFactory.getLogger(UsageService.class); + + /** How many views may accumulate in memory before they are written out. */ + static final int FLUSH_THRESHOLD = 25; + + /** + * The most popularity may multiply a relevance score. + * + *

Bounded deliberately. A resource viewed thousands of times would otherwise swamp textual + * relevance entirely, and because boosted results are seen more often and so viewed more often, + * an unbounded weight compounds into a rich-get-richer loop that new resources cannot break into. + */ + static final double MAX_BOOST = 1.0; + + /** + * How quickly the boost saturates: the view count at which half the maximum boost is reached. + * + *

Small, because the interesting distinction is between a resource nobody opens and one people + * do — not between five hundred views and a thousand. + */ + static final double SATURATION = 5.0; + + private final Dataset assertions; + private final Map pending = new ConcurrentHashMap<>(); + private final AtomicInteger unflushed = new AtomicInteger(); + + /** + * Creates the service. + * + * @param assertions the dataset whose usage graph holds the counts + */ + public UsageService(Dataset assertions) { + this.assertions = assertions; + } + + /** + * Records that a resource was deliberately viewed. + * + *

Buffered in memory, and flushed once {@link #FLUSH_THRESHOLD} views have accumulated. Must + * not be called from inside a transaction: a flush opens its own write transaction. + * + * @param uri the URI of the viewed resource + */ + public void recordView(String uri) { + if (uri == null || uri.isBlank()) { + return; + } + pending.merge(uri, 1L, Long::sum); + if (unflushed.incrementAndGet() >= FLUSH_THRESHOLD) { + flush(); + } + } + + /** + * Writes the buffered views to the usage graph in a single write transaction. + * + *

Each count is re-read and incremented within that transaction, so concurrent writers and a + * restore that replaced the dataset are both accounted for. Safe to call when nothing is pending. + */ + public void flush() { + Map batch = drain(); + if (batch.isEmpty()) { + return; + } + try { + Txn.executeWrite( + assertions, + () -> { + Model usage = assertions.getNamedModel(CortexNamespace.USAGE.getURI()); + batch.forEach((uri, delta) -> increment(usage, uri, delta)); + }); + } catch (RuntimeException e) { + // usage counts are a relevance signal, not data the caller asked us to store; losing a batch + // must not fail the read that happened to trigger the flush + log.warn("Failed to flush {} usage counts; they are lost", batch.size(), e); + } + } + + /** + * Returns the ranking weight of each of the given resources. + * + *

The weight saturates, so popularity nudges the ranking rather than dictating it: a resource + * nobody has opened scores {@code 1.0} and no resource, however popular, exceeds {@code 1 +} + * {@link #MAX_BOOST}. + * + * @param uris the resource URIs to weight + * @return the weight per URI, {@code 1.0} for anything never viewed + */ + public Map weights(Collection uris) { + if (uris.isEmpty()) { + return Map.of(); + } + Map weights = new HashMap<>(); + Txn.executeRead( + assertions, + () -> { + Model usage = assertions.getNamedModel(CortexNamespace.USAGE.getURI()); + uris.forEach( + uri -> weights.put(uri, weight(read(usage, uri) + pending.getOrDefault(uri, 0L)))); + }); + return weights; + } + + /** + * Returns how many times a resource has been viewed, including views not yet flushed. + * + * @param uri the resource URI + * @return the view count, zero if it has never been viewed + */ + public long viewCount(String uri) { + long[] stored = {0}; + Txn.executeRead( + assertions, + () -> stored[0] = read(assertions.getNamedModel(CortexNamespace.USAGE.getURI()), uri)); + return stored[0] + pending.getOrDefault(uri, 0L); + } + + /** + * Converts a view count into a bounded multiplier. + * + * @param count the number of views + * @return the multiplier, between {@code 1.0} and {@code 1 + MAX_BOOST} + */ + static double weight(long count) { + if (count <= 0) { + return 1.0; + } + return 1.0 + MAX_BOOST * (count / (count + SATURATION)); + } + + private Map drain() { + Map batch = new HashMap<>(); + // remove rather than copy-then-clear, so views recorded while the flush runs survive into the + // next batch instead of being dropped + pending.keySet().forEach(uri -> batch.put(uri, pending.remove(uri))); + batch.values().removeIf(java.util.Objects::isNull); + unflushed.set(0); + return batch; + } + + private static long read(Model usage, String uri) { + Statement statement = + usage.getProperty(ResourceFactory.createResource(uri), CortexNamespace.VIEW_COUNT); + return statement == null ? 0 : statement.getLong(); + } + + private static void increment(Model usage, String uri, long delta) { + Resource resource = ResourceFactory.createResource(uri); + long updated = read(usage, uri) + delta; + usage.removeAll(resource, CortexNamespace.VIEW_COUNT, null); + usage.add(resource, CortexNamespace.VIEW_COUNT, usage.createTypedLiteral(updated)); + } +} diff --git a/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java b/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java index 2c6b460..79c6292 100644 --- a/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java +++ b/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java @@ -38,6 +38,14 @@ class SearchTests { :assignedTo kb:SearchAgent ; rdfs:label "Budget planning" ; rdfs:comment "Feeds the quarterly report cycle" . + + kb:AlphaReport a :Task ; + :assignedTo kb:SearchAgent ; + rdfs:label "annual summary" . + + kb:BetaReport a :Task ; + :assignedTo kb:SearchAgent ; + rdfs:label "annual summary" . """; private Cortex cortex; @@ -168,6 +176,43 @@ void shouldReportEachSubjectOnce() { .containsOnlyOnce("communication-api"); } + /** + * Two resources carry the same label, so textual relevance cannot separate them; only how often + * each has been opened can. Viewing one is what promotes it. + */ + @Test + void shouldRankFrequentlyViewedResourcesHigher() { + assertThat(cortex.searchSubjects("annual summary")) + .as("both identically labelled resources match before anything is viewed") + .extracting(result -> result.subject().localName()) + .contains("AlphaReport", "BetaReport"); + + for (int view = 0; view < 10; view++) { + cortex.describe("example://kb/BetaReport"); + } + + List ranked = cortex.searchSubjects("annual summary"); + + assertThat(ranked.getFirst().subject().localName()) + .as("the repeatedly opened resource outranks its identically labelled twin") + .isEqualTo("BetaReport"); + assertThat(ranked.getFirst().score()).isGreaterThan(ranked.getLast().score()); + } + + @Test + void shouldNotLetPopularityOverrideTextualRelevance() { + for (int view = 0; view < 500; view++) { + cortex.describe("example://kb/BetaReport"); + } + + List results = cortex.searchSubjects("quarterly"); + + assertThat(results) + .as("a heavily viewed resource that does not match the text must not appear at all") + .extracting(result -> result.subject().localName()) + .doesNotContain("BetaReport"); + } + @Test void shouldNotMatchUnrelatedShortTokensFuzzily() { List results = cortex.searchSubjects("api"); diff --git a/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java b/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java new file mode 100644 index 0000000..5e9634b --- /dev/null +++ b/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java @@ -0,0 +1,177 @@ +package ai.chatur.cortex.usage; + +import static org.assertj.core.api.Assertions.assertThat; + +import ai.chatur.cortex.core.CortexNamespace; +import ai.chatur.cortex.core.usage.UsageService; +import java.util.List; +import java.util.Map; +import org.apache.jena.query.Dataset; +import org.apache.jena.query.DatasetFactory; +import org.apache.jena.system.Txn; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Behavior tests for view counting and the ranking weight derived from it. */ +class UsageServiceTests { + + private static final String ALPHA = "example://kb/Alpha"; + private static final String BETA = "example://kb/Beta"; + + private Dataset assertions; + private UsageService usage; + + @BeforeEach + void setUp() { + assertions = DatasetFactory.createTxnMem(); + usage = new UsageService(assertions); + } + + @Test + void shouldCountViewsBeforeTheyAreFlushed() { + usage.recordView(ALPHA); + usage.recordView(ALPHA); + + assertThat(usage.viewCount(ALPHA)) + .as("buffered views count immediately, so ranking does not wait for a flush") + .isEqualTo(2); + } + + @Test + void shouldPersistViewsToTheUsageGraphOnFlush() { + usage.recordView(ALPHA); + usage.recordView(ALPHA); + usage.flush(); + + Txn.executeRead( + assertions, + () -> + assertThat(assertions.getNamedModel(CortexNamespace.USAGE.getURI()).size()) + .as("counts land in the reserved usage graph") + .isEqualTo(1)); + assertThat(usage.viewCount(ALPHA)).isEqualTo(2); + } + + @Test + void shouldNotTouchTheDefaultGraph() { + usage.recordView(ALPHA); + usage.flush(); + + Txn.executeRead( + assertions, + () -> + assertThat(assertions.getDefaultModel().isEmpty()) + .as("usage is a reserved named graph; approved assertions are untouched") + .isTrue()); + } + + @Test + void shouldAccumulateAcrossFlushesRatherThanOverwrite() { + usage.recordView(ALPHA); + usage.flush(); + usage.recordView(ALPHA); + usage.recordView(ALPHA); + usage.flush(); + + assertThat(usage.viewCount(ALPHA)) + .as("each flush increments the stored total instead of replacing it") + .isEqualTo(3); + } + + /** + * A restore replaces the whole assertions dataset partway through startup. Because only unflushed + * deltas are held in memory and the current value is re-read inside the flush transaction, counts + * written by whoever produced the backup survive. + */ + @Test + void shouldIncrementOntoCountsThatAppearedAfterConstruction() { + Txn.executeWrite( + assertions, + () -> + assertions + .getNamedModel(CortexNamespace.USAGE.getURI()) + .add( + assertions.getDefaultModel().createResource(ALPHA), + CortexNamespace.VIEW_COUNT, + assertions.getDefaultModel().createTypedLiteral(40L))); + + usage.recordView(ALPHA); + usage.flush(); + + assertThat(usage.viewCount(ALPHA)) + .as("a count restored after this service was constructed is added to, not clobbered") + .isEqualTo(41); + } + + @Test + void shouldFlushAutomaticallyOnceEnoughViewsAccumulate() { + for (int view = 0; view < 100; view++) { + usage.recordView(ALPHA); + } + + Txn.executeRead( + assertions, + () -> + assertThat(assertions.getNamedModel(CortexNamespace.USAGE.getURI()).isEmpty()) + .as("views are written out in batches rather than one transaction per view") + .isFalse()); + } + + @Test + void shouldIgnoreBlankIdentifiers() { + usage.recordView(null); + usage.recordView(" "); + usage.flush(); + + Txn.executeRead( + assertions, + () -> + assertThat(assertions.getNamedModel(CortexNamespace.USAGE.getURI()).isEmpty()) + .isTrue()); + } + + @Test + void shouldWeightUnviewedResourcesNeutrally() { + Map weights = usage.weights(List.of(ALPHA, BETA)); + + assertThat(weights.get(ALPHA)).isEqualTo(1.0); + assertThat(weights.get(BETA)).isEqualTo(1.0); + } + + @Test + void shouldWeightViewedResourcesAboveUnviewedOnes() { + for (int view = 0; view < 10; view++) { + usage.recordView(BETA); + } + + Map weights = usage.weights(List.of(ALPHA, BETA)); + + assertThat(weights.get(BETA)).isGreaterThan(weights.get(ALPHA)); + } + + @Test + void shouldSaturateSoPopularityNeverSwampsRelevance() { + seedCount(ALPHA, 10); + seedCount(BETA, 1_000_000); + + Map weights = usage.weights(List.of(ALPHA, BETA)); + + assertThat(weights.get(BETA)) + .as("the weight rises with views but is bounded, so nothing dominates on popularity alone") + .isGreaterThan(weights.get(ALPHA)) + .isLessThanOrEqualTo(2.0); + assertThat(weights.get(ALPHA)).isGreaterThan(1.0); + } + + private void seedCount(String uri, long count) { + Txn.executeWrite( + assertions, + () -> + assertions + .getNamedModel(CortexNamespace.USAGE.getURI()) + .add( + assertions.getDefaultModel().createResource(uri), + CortexNamespace.VIEW_COUNT, + assertions.getDefaultModel().createTypedLiteral(count))); + } +} diff --git a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java index a84b347..efcd4ba 100644 --- a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java +++ b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java @@ -21,6 +21,7 @@ import ai.chatur.cortex.core.stats.StatsService; import ai.chatur.cortex.core.store.AssertionStore; import ai.chatur.cortex.core.store.TextIndexFactory; +import ai.chatur.cortex.core.usage.UsageService; import ai.chatur.cortex.spring.inference.InferenceInitializer; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -42,7 +43,8 @@ /** * Core auto-configuration for Cortex: the ontology, SHACL shapes, rule reasoner, the two Jena - * {@link Dataset}s, the eleven core services, and the composed {@link Cortex} bean. + * {@link Dataset}s, the eleven core services composed into {@link Cortex}, the {@link UsageService} + * that weights search ranking, and the composed {@link Cortex} bean. * *

Every bean here is {@link ConditionalOnMissingBean @ConditionalOnMissingBean}, so a consumer * may substitute their own {@link OntModel}, {@link Shapes}, {@link Dataset}, {@link @@ -283,12 +285,28 @@ Dataset inferences() { return TextIndexFactory.open(DatasetFactory.createTxnMem()); } + /** + * Creates the service recording how often each resource is viewed. + * + *

{@code destroyMethod} flushes the views buffered since the last batch, so an orderly + * shutdown does not discard them. + * + * @param assertions the assertions dataset, whose usage graph holds the counts + * @return the usage service + */ + @Bean(destroyMethod = "flush") + @ConditionalOnMissingBean + UsageService usageService(@Qualifier("assertions") Dataset assertions) { + return new UsageService(assertions); + } + /** * Creates the service answering SPARQL queries and full-text search. * * @param inferences the indexed inference dataset * @param assertions the assertions dataset, used to look up provenance * @param ontModel the ontology model, used to abbreviate terms for display + * @param usageService view counts, which weight the ranking of search results * @return the query service */ @Bean @@ -296,8 +314,9 @@ Dataset inferences() { QueryService queryService( @Qualifier("inferences") Dataset inferences, @Qualifier("assertions") Dataset assertions, - OntModel ontModel) { - return new QueryService(inferences, assertions, ontModel); + OntModel ontModel, + UsageService usageService) { + return new QueryService(inferences, assertions, ontModel, usageService); } /** From d84910dc9400ca3c09c78076ee43c9c8adf80162 Mon Sep 17 00:00:00 2001 From: Ajay Viswanathan Date: Sun, 19 Jul 2026 07:01:49 +0700 Subject: [PATCH 2/2] [feature] decays view weighting over a configurable half-life Search ranking weights each resource by how often it is opened. Without decay a resource popular a year ago outranks a newer one indefinitely, so a view's contribution now halves every cortex.search.viewHalfLife (default 30d; 0 disables decay and restores plain lifetime counting). cortex:viewCount is therefore no longer a tally but a decayed score, meaningless without the cortex:viewCountUpdated instant beside it. Storing a timestamped event per view would grow without bound, so each resource keeps one score plus when it was last recomputed, and the discount is computed from that. Changing the half-life takes effect immediately, with no stored history to migrate. The discount is applied on read as well as on write. Applying it only on write would leave a resource nobody has opened since holding a stale score until the moment someone opened it again -- exactly backwards. A missing timestamp means "current" rather than the epoch, so counts written before decay existed are not silently wiped on first read. CortexBuilder.DEFAULT_VIEW_HALF_LIFE and the property default must stay equal; the two assembly paths are required to produce identical graphs. Also replaces the note-pad search fixtures' previous naming, which had leaked domain vocabulary into the test corpus and the published docs, and documents the ranking model in README, CLAUDE.md, and the site. The site states plainly that this is a query-independent ranking prior and not Hebbian learning: each resource carries its own score, and nothing strengthens a connection between two resources. Co-Authored-By: Claude Opus 4.8 --- CLAUDE.md | 26 ++-- README.md | 1 + .../java/ai/chatur/cortex/CortexBuilder.java | 28 +++- .../chatur/cortex/core/CortexNamespace.java | 11 +- .../cortex/core/query/QueryService.java | 6 +- .../cortex/core/store/TextIndexFactory.java | 4 +- .../cortex/core/usage/UsageService.java | 147 ++++++++++++++---- .../ai/chatur/cortex/query/SearchTests.java | 54 ++++--- .../cortex/usage/UsageServiceTests.java | 134 ++++++++++++++-- .../spring/CortexAutoConfiguration.java | 6 +- .../cortex/spring/CortexProperties.java | 18 +++ site/architecture.html | 27 ++++ site/configuration.html | 1 + 13 files changed, 376 insertions(+), 87 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 05116e4..d5bd1ab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -158,16 +158,16 @@ deterministic. Don't hand-roll a fourth. runs the user's input through `TextIndexFactory.analyzer()`, *not* `split("\\s+")`. Lucene's classic parser resolves fuzzy and other multi-term queries via `Analyzer.normalize()`, which lower-cases but does **not** tokenize — so a hand-split term is looked up whole against an index the tokenizer already -split differently. That is why `communication-api` returned nothing while `communication api` worked: -the index held `communication` and `api`, and at the default edit distance of 2 neither is within -reach of the 17-character term. The analyzer is a single shared instance for exactly this reason; two +split differently. That is why `note-pad` returned nothing while `note pad` worked: +the index held `note` and `pad`, and at the default edit distance of 2 neither is within +reach of the 8-character term. The analyzer is a single shared instance for exactly this reason; two instances that tokenize differently would break search silently rather than loudly. `SearchTests` pins the hyphen, slash, and comma cases. Note `_` and `.` legitimately do **not** split (UAX#29 joins letters across them, the rule that keeps `example.com` intact) — a literal written that way indexes as one token too, so query and index still agree. **Fuzziness is graded by token length, never bare `~`.** A bare `~` is edit distance 2, which on a -three-character token like `api` reaches most short terms in the index. Tokens ≤ 3 characters are +three-character token like `pad` reaches most short terms in the index. Tokens ≤ 3 characters are matched exactly, 4–6 allow one edit, longer ones two. **`text:query` must name the property to make `?match` usable.** The index resolves the property to @@ -198,12 +198,22 @@ restored counts at the next flush. The current value is re-read *inside* the flu making the update a true increment; `UsageServiceTests` pins this. Don't "optimize" it into a cached map — the bug it reintroduces is silent and only shows up on restored replicas. -**The popularity weight is bounded and saturating** (`1 + count/(count+5)`, capped at 2×). Raw counts +**The popularity weight is bounded and saturating** (`1 + score/(score+5)`, capped at 2×). Raw counts would let one hot resource swamp textual relevance, and since boosted results get viewed more, an unbounded weight compounds into a rich-get-richer loop new resources cannot break into. Re-ranking happens over the whole candidate set, not a truncated head — truncating first means a popular resource low in the candidates can never be promoted, which defeats the point. +**`cortex:viewCount` is a decayed score, not a tally, and is meaningless without +`cortex:viewCountUpdated`.** It halves every `cortex.search.view-half-life` (default `30d`; `0` +disables decay). Rather than storing a timestamped event per view — unbounded growth — each resource +keeps one score plus the instant it was last recomputed; the discount is applied **on read as well as +on write**, or a resource nobody has opened since would keep a stale score until someone opened it +again. Changing the half-life takes effect immediately with no history to migrate. A **missing** +timestamp means "current", not the epoch: counts written before decay existed would otherwise be +wiped on first read. `CortexBuilder.DEFAULT_VIEW_HALF_LIFE` and the property default must stay equal — +the two assembly paths are required to produce identical graphs. + **`rdf:type` is deliberately not indexed.** It was, into the same field as `rdfs:label`, which mixed class-URI tokens into the same relevance space as human-readable prose and gave every typed resource the same filler terms. @@ -275,10 +285,8 @@ has nothing to restore; every other failure propagates and fails the boot. upload is a copy, not a move, deliberately: deleting the local file on a successful upload would make a bucket misconfiguration destructive. This is the `.cortex/` residue problem below, now with a scheduler behind it. Retention belongs to the volume, or to an S3 lifecycle rule. -- View counts have **no time decay**: a resource popular a year ago still outranks a newer one - forever. The bound keeps this from being severe, but recency weighting is the natural next step. - Counts also never expire for deleted resources — a rejected or removed subject keeps its row in - `cortex://usage`. +- Nothing prunes `cortex://usage`: a rejected or removed subject keeps its row forever. Decay makes + the score irrelevant quickly, but the triples remain. - Counts are lost under the default `cortex.persistent=false`, since the assertions dataset is then in-memory. That matches the text index and the inference closure, and is a non-issue in production. - ~335 MB of gitignored `.cortex/` runtime residue sits in the tree (repo root and the example) from diff --git a/README.md b/README.md index c6813a5..556c76c 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ All properties are bound under the `cortex` prefix. `ontologies`, `shapes`, and | `cortex.ontologies` | `classpath:ontology.ttl` | The ontologies the knowledge graph is built on, in Turtle syntax, merged in order. | | `cortex.shapes` | `classpath:ontology.shapes` | The SHACL shapes ingested assertions are validated against, in Turtle syntax, merged in order. | | `cortex.rules` | `classpath:ontology.rules` | The Jena rules used for inference, concatenated in order. | +| `cortex.search.viewHalfLife` | `30d` | How long it takes a view's contribution to search ranking to halve. Results are ranked by textual relevance, then weighted by how often each resource has been deliberately opened, so a frequently consulted resource outranks an equally relevant one nobody reads. This controls how quickly that interest fades. Set to `0` to disable decay and weight by the raw lifetime count, in which case a resource popular long ago outranks a newer one indefinitely. The weight is bounded either way, so popularity reorders comparable results rather than overriding relevance. | | `cortex.web.enabled` | `true` | Whether the web UI controllers are registered. Set to `false` to get the knowledge graph without the UI, without excluding individual controller beans. | | `cortex.mcp.enabled` | `true` | Whether the MCP tools and resources are registered. Set to `false` to get the knowledge graph without an MCP server, without excluding individual tool beans. | | `cortex.backup.enabled` | `false` | Whether the scheduled backup job is registered. See [Scheduled backups](#scheduled-backups) — enabling it requires `cortex.persistent=true`, an enabled S3 client, and two extra dependencies. | diff --git a/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java b/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java index b27fb31..fbbf673 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java @@ -19,6 +19,7 @@ import ai.chatur.cortex.core.store.AssertionStore; import ai.chatur.cortex.core.store.TextIndexFactory; import ai.chatur.cortex.core.usage.UsageService; +import java.time.Duration; import java.util.List; import org.apache.jena.ontapi.model.OntModel; import org.apache.jena.query.Dataset; @@ -48,10 +49,19 @@ */ public final class CortexBuilder { + /** + * The default half-life of a view's contribution to search ranking. + * + *

Mirrors {@code cortex.search.view-half-life}, whose default must match: the two assembly + * paths are required to produce identical graphs. + */ + public static final Duration DEFAULT_VIEW_HALF_LIFE = Duration.ofDays(30); + private List ontologies = List.of(); private List shapes = List.of(); private List rules = List.of(); private String assertionsLocation; + private Duration viewHalfLife = DEFAULT_VIEW_HALF_LIFE; private CortexBuilder() {} @@ -112,6 +122,22 @@ public CortexBuilder persistent(String assertionsLocation) { return this; } + /** + * Sets how long it takes a view's contribution to search ranking to halve. + * + *

Search results are weighted by how often each resource is deliberately opened; this controls + * how quickly that interest fades, so recent attention counts for more than attention that has + * since moved on. Pass {@link Duration#ZERO} to disable decay and weight by the raw lifetime + * count instead. + * + * @param viewHalfLife the half-life, or {@link Duration#ZERO} to disable decay + * @return this builder, for chaining + */ + public CortexBuilder viewHalfLife(Duration viewHalfLife) { + this.viewHalfLife = viewHalfLife; + return this; + } + /** * Assembles the knowledge graph. * @@ -140,7 +166,7 @@ public Cortex build() { new BranchMergeService(assertions, branchRepository, provenanceRecorder); ArchiveService archiveService = new ArchiveService(assertions); InferenceService inferenceService = new InferenceService(assertions, inferences, reasoner); - UsageService usageService = new UsageService(assertions); + UsageService usageService = new UsageService(assertions, viewHalfLife); QueryService queryService = new QueryService(inferences, assertions, ontModel, usageService); StatsService statsService = new StatsService(assertions, inferences, ontModel, parsedShapes, parsedRules); diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java b/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java index 9812d90..761d3b6 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/CortexNamespace.java @@ -22,9 +22,18 @@ public final class CortexNamespace { */ public static final Resource USAGE = ResourceFactory.createResource(NS + "usage"); - /** The property recording how many times a resource has been viewed, within {@link #USAGE}. */ + /** + * The property recording a resource's time-decayed view score, within {@link #USAGE}. + * + *

Not a plain tally: the value is discounted towards zero as it ages, so it is only meaningful + * alongside {@link #VIEW_COUNT_UPDATED}, which says when it was last brought up to date. + */ public static final Property VIEW_COUNT = ResourceFactory.createProperty(NS + "viewCount"); + /** The instant {@link #VIEW_COUNT} was last recomputed, within {@link #USAGE}. */ + public static final Property VIEW_COUNT_UPDATED = + ResourceFactory.createProperty(NS + "viewCountUpdated"); + private CortexNamespace() {} /** diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java b/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java index 5d6fde8..916b9f7 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/query/QueryService.java @@ -338,8 +338,8 @@ private static SearchResult weighted(SearchResult result, double weight) { *

The input is tokenized with {@link TextIndexFactory#analyzer() the index's own analyzer} * rather than split on whitespace. Lucene's classic query parser resolves fuzzy terms through * {@code Analyzer.normalize}, which lower-cases but does not tokenize, so a hand-split term such - * as {@code communication-api} would be looked up whole against an index whose tokenizer had - * already split it into {@code communication} and {@code api} — and match nothing. + * as {@code note-pad} would be looked up whole against an index whose tokenizer had already split + * it into {@code note} and {@code pad} — and match nothing. * *

Every token is required, so adding a word narrows the result set rather than widening it. */ @@ -383,7 +383,7 @@ private static List analyze(String text) { * Grades edit distance by token length. * *

A bare {@code ~} is edit distance 2, which on a short token matches a large share of the - * index — {@code api} would reach every three-to-five character term. Short tokens are therefore + * index — {@code pad} would reach every three-to-five character term. Short tokens are therefore * matched exactly, and only longer ones, where two edits are a small fraction of the token, get * the full allowance. * diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/store/TextIndexFactory.java b/cortex-core/src/main/java/ai/chatur/cortex/core/store/TextIndexFactory.java index fe8a31d..de0327c 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/core/store/TextIndexFactory.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/store/TextIndexFactory.java @@ -43,8 +43,8 @@ private TextIndexFactory() {} * same analyzer. Lucene's classic query parser resolves fuzzy and other multi-term queries * through {@link Analyzer#normalize}, which lower-cases but does not tokenize, so a * query term assembled by hand never matches an index term that the tokenizer split differently — - * {@code communication-api} against an index holding {@code communication} and {@code api}, for - * instance. Sharing one instance is what keeps query analysis and index analysis from drifting. + * {@code note-pad} against an index holding {@code note} and {@code pad}, for instance. Sharing + * one instance is what keeps query analysis and index analysis from drifting. * * @return the shared analyzer used for both indexing and querying */ diff --git a/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java b/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java index c74a05b..3a56275 100644 --- a/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java +++ b/cortex-core/src/main/java/ai/chatur/cortex/core/usage/UsageService.java @@ -1,11 +1,16 @@ package ai.chatur.cortex.core.usage; import ai.chatur.cortex.core.CortexNamespace; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.query.Dataset; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; @@ -17,7 +22,7 @@ /** * Counts how often each resource is deliberately viewed, and turns those counts into a search - * ranking weight. + * ranking weight that fades as views age. * *

Only deliberate views are counted — opening a resource, not merely appearing in a result list. * Counting search impressions would boost whatever already ranked highly, which is self-fulfilling @@ -27,6 +32,13 @@ * reserved named graph alongside provenance. Writing there does not touch the default graph, so the * rule that approved assertions are only ever reached through review still holds. * + *

Views decay with age. The stored value is not a tally but a score halved + * every {@code halfLife}, so what the graph's users consult *now* outranks what was popular a year + * ago. Rather than keeping a timestamped event per view — which would grow without bound — each + * resource keeps one score and the instant it was last brought up to date; the discount is applied + * on read and folded in on write. Changing the half-life therefore takes effect immediately, with + * no stored history to migrate. A half-life of zero disables decay, making the score a plain tally. + * *

Views are not written as they happen. TDB2 admits a single writer, so a write * transaction per view would serialize the read path against ingestion. Views accumulate in memory * and are flushed in batches; a crash loses at most {@link #FLUSH_THRESHOLD} views, which is @@ -54,7 +66,7 @@ public class UsageService { static final double MAX_BOOST = 1.0; /** - * How quickly the boost saturates: the view count at which half the maximum boost is reached. + * How quickly the boost saturates: the score at which half the maximum boost is reached. * *

Small, because the interesting distinction is between a resource nobody opens and one people * do — not between five hundred views and a thousand. @@ -62,16 +74,34 @@ public class UsageService { static final double SATURATION = 5.0; private final Dataset assertions; + private final Duration halfLife; + private final Clock clock; private final Map pending = new ConcurrentHashMap<>(); private final AtomicInteger unflushed = new AtomicInteger(); /** - * Creates the service. + * Creates the service using the system clock. + * + * @param assertions the dataset whose usage graph holds the counts + * @param halfLife how long it takes a view's contribution to lose half its weight; zero or + * negative disables decay, making the score a plain tally + */ + public UsageService(Dataset assertions, Duration halfLife) { + this(assertions, halfLife, Clock.systemUTC()); + } + + /** + * Creates the service with an explicit clock. * * @param assertions the dataset whose usage graph holds the counts + * @param halfLife how long it takes a view's contribution to lose half its weight; zero or + * negative disables decay, making the score a plain tally + * @param clock the source of the current time, which decay is measured against */ - public UsageService(Dataset assertions) { + public UsageService(Dataset assertions, Duration halfLife, Clock clock) { this.assertions = assertions; + this.halfLife = halfLife == null ? Duration.ZERO : halfLife; + this.clock = clock; } /** @@ -95,8 +125,9 @@ public void recordView(String uri) { /** * Writes the buffered views to the usage graph in a single write transaction. * - *

Each count is re-read and incremented within that transaction, so concurrent writers and a - * restore that replaced the dataset are both accounted for. Safe to call when nothing is pending. + *

Each score is re-read, decayed to the present, and incremented within that transaction, so + * concurrent writers and a restore that replaced the dataset are both accounted for. Safe to call + * when nothing is pending. */ public void flush() { Map batch = drain(); @@ -104,11 +135,12 @@ public void flush() { return; } try { + Instant now = clock.instant(); Txn.executeWrite( assertions, () -> { Model usage = assertions.getNamedModel(CortexNamespace.USAGE.getURI()); - batch.forEach((uri, delta) -> increment(usage, uri, delta)); + batch.forEach((uri, delta) -> increment(usage, uri, delta, now)); }); } catch (RuntimeException e) { // usage counts are a relevance signal, not data the caller asked us to store; losing a batch @@ -122,7 +154,8 @@ public void flush() { * *

The weight saturates, so popularity nudges the ranking rather than dictating it: a resource * nobody has opened scores {@code 1.0} and no resource, however popular, exceeds {@code 1 +} - * {@link #MAX_BOOST}. + * {@link #MAX_BOOST}. Scores are decayed to the present before weighting, so a resource that was + * popular long ago and has not been opened since ranks as though it were not. * * @param uris the resource URIs to weight * @return the weight per URI, {@code 1.0} for anything never viewed @@ -131,42 +164,90 @@ public Map weights(Collection uris) { if (uris.isEmpty()) { return Map.of(); } + Instant now = clock.instant(); Map weights = new HashMap<>(); Txn.executeRead( assertions, () -> { Model usage = assertions.getNamedModel(CortexNamespace.USAGE.getURI()); - uris.forEach( - uri -> weights.put(uri, weight(read(usage, uri) + pending.getOrDefault(uri, 0L)))); + uris.forEach(uri -> weights.put(uri, weight(score(usage, uri, now)))); }); return weights; } /** - * Returns how many times a resource has been viewed, including views not yet flushed. + * Returns a resource's decayed view score, including views not yet flushed. + * + *

Equal to the number of views only when decay is disabled or no time has passed; otherwise + * older views contribute less than newer ones. * * @param uri the resource URI - * @return the view count, zero if it has never been viewed + * @return the decayed score, zero if the resource has never been viewed */ - public long viewCount(String uri) { - long[] stored = {0}; + public double viewScore(String uri) { + Instant now = clock.instant(); + double[] stored = {0}; Txn.executeRead( assertions, - () -> stored[0] = read(assertions.getNamedModel(CortexNamespace.USAGE.getURI()), uri)); - return stored[0] + pending.getOrDefault(uri, 0L); + () -> + stored[0] = score(assertions.getNamedModel(CortexNamespace.USAGE.getURI()), uri, now)); + return stored[0]; } /** - * Converts a view count into a bounded multiplier. + * Converts a decayed view score into a bounded multiplier. * - * @param count the number of views + * @param score the decayed view score * @return the multiplier, between {@code 1.0} and {@code 1 + MAX_BOOST} */ - static double weight(long count) { - if (count <= 0) { + static double weight(double score) { + if (score <= 0) { + return 1.0; + } + return 1.0 + MAX_BOOST * (score / (score + SATURATION)); + } + + /** + * Discounts a score for the time elapsed since it was last updated. + * + * @param elapsed how long ago the score was current + * @return the fraction of the score that survives, {@code 1.0} when decay is disabled + */ + private double decay(Duration elapsed) { + if (halfLife.isZero() || halfLife.isNegative() || elapsed.isNegative() || elapsed.isZero()) { return 1.0; } - return 1.0 + MAX_BOOST * (count / (count + SATURATION)); + return Math.pow(0.5, (double) elapsed.toMillis() / halfLife.toMillis()); + } + + /** Reads a resource's stored score and brings it forward to {@code now}, adding pending views. */ + private double score(Model usage, String uri, Instant now) { + Resource resource = ResourceFactory.createResource(uri); + Statement stored = usage.getProperty(resource, CortexNamespace.VIEW_COUNT); + double decayed = + stored == null + ? 0 + : stored.getDouble() * decay(Duration.between(updatedAt(usage, resource, now), now)); + return decayed + pending.getOrDefault(uri, 0L); + } + + /** + * Reads when a resource's score was last updated. + * + *

A missing timestamp is treated as the present rather than the epoch: counts written before + * decay existed would otherwise be wiped out the first time they were read. + */ + private static Instant updatedAt(Model usage, Resource resource, Instant now) { + Statement statement = usage.getProperty(resource, CortexNamespace.VIEW_COUNT_UPDATED); + if (statement == null) { + return now; + } + try { + return Instant.parse(statement.getString()); + } catch (RuntimeException e) { + log.warn("Unreadable usage timestamp on {}; treating the score as current", resource, e); + return now; + } } private Map drain() { @@ -174,21 +255,25 @@ private Map drain() { // remove rather than copy-then-clear, so views recorded while the flush runs survive into the // next batch instead of being dropped pending.keySet().forEach(uri -> batch.put(uri, pending.remove(uri))); - batch.values().removeIf(java.util.Objects::isNull); + batch.values().removeIf(Objects::isNull); unflushed.set(0); return batch; } - private static long read(Model usage, String uri) { - Statement statement = - usage.getProperty(ResourceFactory.createResource(uri), CortexNamespace.VIEW_COUNT); - return statement == null ? 0 : statement.getLong(); - } - - private static void increment(Model usage, String uri, long delta) { + private void increment(Model usage, String uri, long delta, Instant now) { Resource resource = ResourceFactory.createResource(uri); - long updated = read(usage, uri) + delta; + Statement stored = usage.getProperty(resource, CortexNamespace.VIEW_COUNT); + double decayed = + stored == null + ? 0 + : stored.getDouble() * decay(Duration.between(updatedAt(usage, resource, now), now)); + usage.removeAll(resource, CortexNamespace.VIEW_COUNT, null); - usage.add(resource, CortexNamespace.VIEW_COUNT, usage.createTypedLiteral(updated)); + usage.removeAll(resource, CortexNamespace.VIEW_COUNT_UPDATED, null); + usage.add(resource, CortexNamespace.VIEW_COUNT, usage.createTypedLiteral(decayed + delta)); + usage.add( + resource, + CortexNamespace.VIEW_COUNT_UPDATED, + usage.createTypedLiteral(now.toString(), XSDDatatype.XSDdateTime)); } } diff --git a/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java b/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java index 79c6292..4ac1c47 100644 --- a/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java +++ b/cortex-core/src/test/java/ai/chatur/cortex/query/SearchTests.java @@ -29,10 +29,10 @@ class SearchTests { :assignedTo kb:SearchAgent ; rdfs:label "quarterly report" . - kb:communication-api a :Task ; + kb:note-pad a :Task ; :assignedTo kb:SearchAgent ; - rdfs:label "Communication API" ; - rdfs:comment "Handles inbound and outbound messaging for partner systems" . + rdfs:label "Note Pad" ; + rdfs:comment "Collects sketches and jottings for later" . kb:BudgetTask a :Task ; :assignedTo kb:SearchAgent ; @@ -81,29 +81,28 @@ void shouldSearchSubjects() { * *

Splitting the query on whitespace and appending {@code ~} forces every token down Lucene's * fuzzy multi-term path, which resolves terms via {@code Analyzer.normalize()} — lower-casing - * only, no tokenization. {@code communication-api} therefore stayed one term, while the index - * (tokenized by {@code StandardAnalyzer}'s UAX#29 tokenizer) held only {@code communication} and - * {@code api}. At the default edit distance of 2 nothing matched, and the search silently - * returned nothing. + * only, no tokenization. {@code note-pad} therefore stayed one term, while the index (tokenized + * by {@code StandardAnalyzer}'s UAX#29 tokenizer) held only {@code note} and {@code pad}. At the + * default edit distance of 2 nothing matched, and the search silently returned nothing. */ @Test void shouldFindResourceWhenQueryIsHyphenated() { - List results = cortex.searchSubjects("communication-api"); + List results = cortex.searchSubjects("note-pad"); assertThat(results) .as("a hyphenated query must match the same resource as its whitespace-separated form") .extracting(result -> result.subject().localName()) - .contains("communication-api"); + .contains("note-pad"); } @Test void shouldFindResourceWhenQueryIsWhitespaceSeparated() { - List results = cortex.searchSubjects("communication api"); + List results = cortex.searchSubjects("note pad"); assertThat(results) .as("the already-working path must keep working") .extracting(result -> result.subject().localName()) - .contains("communication-api"); + .contains("note-pad"); } /** @@ -111,43 +110,43 @@ void shouldFindResourceWhenQueryIsWhitespaceSeparated() { * *

{@code _} and {@code .} are deliberately absent: UAX#29 joins letters across them ({@code * ExtendNumLet} and {@code MidNumLet} — the rule that keeps {@code example.com} in one piece), so - * {@code communication_api} is a single token. That is consistent rather than broken, because a - * literal written that way indexes as a single token too; query and index analysis still agree, - * which is the property that matters. + * {@code note_pad} is a single token. That is consistent rather than broken, because a literal + * written that way indexes as a single token too; query and index analysis still agree, which is + * the property that matters. */ @Test void shouldFindResourceRegardlessOfSeparator() { - for (String query : List.of("communication/api", "communication,api", "Communication API")) { + for (String query : List.of("note/pad", "note,pad", "Note Pad")) { assertThat(cortex.searchSubjects(query)) .as("query %s must analyze to the same tokens as the indexed label", query) .extracting(result -> result.subject().localName()) - .contains("communication-api"); + .contains("note-pad"); } } @Test void shouldNarrowResultsAsTermsAreAdded() { - List broad = cortex.searchSubjects("communication"); - List narrow = cortex.searchSubjects("communication quarterly"); + List broad = cortex.searchSubjects("note"); + List narrow = cortex.searchSubjects("note quarterly"); - assertThat(broad).as("the single-term query matches the Communication API task").isNotEmpty(); + assertThat(broad).as("the single-term query matches the Note Pad task").isNotEmpty(); assertThat(narrow) .as("every term is required, so an unrelated extra term must not widen the results") .hasSizeLessThanOrEqualTo(broad.size()); assertThat(narrow) .as("no resource carries both terms in one literal") .extracting(result -> result.subject().localName()) - .doesNotContain("communication-api"); + .doesNotContain("note-pad"); } @Test void shouldFindResourceByComment() { - List results = cortex.searchSubjects("messaging"); + List results = cortex.searchSubjects("sketches"); assertThat(results) .as("comments are indexed in their own field and remain searchable") .extracting(result -> result.subject().localName()) - .contains("communication-api"); + .contains("note-pad"); assertThat(results.getFirst().match()) .as("the matching literal is reported for comment hits too, not only label hits") .isNotNull(); @@ -168,12 +167,12 @@ void shouldRankLabelMatchesAboveCommentMatches() { @Test void shouldReportEachSubjectOnce() { - List results = cortex.searchSubjects("communication"); + List results = cortex.searchSubjects("note"); assertThat(results) .as("the label and comment of one resource are separate documents but one result") .extracting(result -> result.subject().localName()) - .containsOnlyOnce("communication-api"); + .containsOnlyOnce("note-pad"); } /** @@ -215,12 +214,11 @@ void shouldNotLetPopularityOverrideTextualRelevance() { @Test void shouldNotMatchUnrelatedShortTokensFuzzily() { - List results = cortex.searchSubjects("api"); + List results = cortex.searchSubjects("pad"); assertThat(results) - .as("short tokens are matched exactly, so 'api' must not fuzzily reach 'a', 'apt', etc.") + .as("short tokens are matched exactly, so 'pad' must not fuzzily reach 'pat', 'bad', etc.") .isNotEmpty() - .allSatisfy( - result -> assertThat(result.subject().localName()).isEqualTo("communication-api")); + .allSatisfy(result -> assertThat(result.subject().localName()).isEqualTo("note-pad")); } } diff --git a/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java b/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java index 5e9634b..d3afe2c 100644 --- a/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java +++ b/cortex-core/src/test/java/ai/chatur/cortex/usage/UsageServiceTests.java @@ -4,6 +4,11 @@ import ai.chatur.cortex.core.CortexNamespace; import ai.chatur.cortex.core.usage.UsageService; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.List; import java.util.Map; import org.apache.jena.query.Dataset; @@ -18,13 +23,17 @@ class UsageServiceTests { private static final String ALPHA = "example://kb/Alpha"; private static final String BETA = "example://kb/Beta"; + private static final Instant START = Instant.parse("2026-01-01T00:00:00Z"); + private Dataset assertions; + private MutableClock clock; private UsageService usage; @BeforeEach void setUp() { + clock = new MutableClock(START); assertions = DatasetFactory.createTxnMem(); - usage = new UsageService(assertions); + usage = new UsageService(assertions, Duration.ofDays(30), clock); } @Test @@ -32,9 +41,9 @@ void shouldCountViewsBeforeTheyAreFlushed() { usage.recordView(ALPHA); usage.recordView(ALPHA); - assertThat(usage.viewCount(ALPHA)) + assertThat(usage.viewScore(ALPHA)) .as("buffered views count immediately, so ranking does not wait for a flush") - .isEqualTo(2); + .isEqualTo(2.0); } @Test @@ -47,9 +56,9 @@ void shouldPersistViewsToTheUsageGraphOnFlush() { assertions, () -> assertThat(assertions.getNamedModel(CortexNamespace.USAGE.getURI()).size()) - .as("counts land in the reserved usage graph") - .isEqualTo(1)); - assertThat(usage.viewCount(ALPHA)).isEqualTo(2); + .as("the reserved usage graph holds the score and the instant it was computed") + .isEqualTo(2)); + assertThat(usage.viewScore(ALPHA)).isEqualTo(2.0); } @Test @@ -73,9 +82,9 @@ void shouldAccumulateAcrossFlushesRatherThanOverwrite() { usage.recordView(ALPHA); usage.flush(); - assertThat(usage.viewCount(ALPHA)) + assertThat(usage.viewScore(ALPHA)) .as("each flush increments the stored total instead of replacing it") - .isEqualTo(3); + .isEqualTo(3.0); } /** @@ -98,9 +107,9 @@ void shouldIncrementOntoCountsThatAppearedAfterConstruction() { usage.recordView(ALPHA); usage.flush(); - assertThat(usage.viewCount(ALPHA)) + assertThat(usage.viewScore(ALPHA)) .as("a count restored after this service was constructed is added to, not clobbered") - .isEqualTo(41); + .isEqualTo(41.0); } @Test @@ -163,6 +172,82 @@ void shouldSaturateSoPopularityNeverSwampsRelevance() { assertThat(weights.get(ALPHA)).isGreaterThan(1.0); } + @Test + void shouldFadeViewsAsTheyAge() { + for (int view = 0; view < 8; view++) { + usage.recordView(ALPHA); + } + usage.flush(); + double fresh = usage.viewScore(ALPHA); + + clock.advance(Duration.ofDays(30)); + + assertThat(usage.viewScore(ALPHA)) + .as("one half-life on, the same views count for half as much") + .isCloseTo(fresh / 2, org.assertj.core.data.Offset.offset(0.01)); + } + + @Test + void shouldRankRecentInterestAboveFadedInterest() { + for (int view = 0; view < 10; view++) { + usage.recordView(ALPHA); + } + usage.flush(); + + clock.advance(Duration.ofDays(365)); + usage.recordView(BETA); + usage.flush(); + + Map weights = usage.weights(List.of(ALPHA, BETA)); + + assertThat(weights.get(BETA)) + .as("a single recent view outweighs ten views from a year ago") + .isGreaterThan(weights.get(ALPHA)); + } + + @Test + void shouldDecayOnReadWithoutRequiringAWrite() { + usage.recordView(ALPHA); + usage.flush(); + double fresh = usage.viewScore(ALPHA); + + clock.advance(Duration.ofDays(120)); + + assertThat(usage.viewScore(ALPHA)) + .as("a resource nobody has opened since must fade without waiting for another view") + .isLessThan(fresh); + } + + @Test + void shouldNotDecayWhenHalfLifeIsZero() { + UsageService undecayed = new UsageService(assertions, Duration.ZERO, clock); + for (int view = 0; view < 4; view++) { + undecayed.recordView(ALPHA); + } + undecayed.flush(); + + clock.advance(Duration.ofDays(3650)); + + assertThat(undecayed.viewScore(ALPHA)) + .as("a zero half-life turns the score back into a plain lifetime tally") + .isEqualTo(4.0); + } + + /** + * Counts written before decay existed carry no timestamp. Treating that as the epoch would wipe + * them out on first read, so a missing timestamp means "current". + */ + @Test + void shouldTreatCountsWithoutATimestampAsCurrent() { + seedCount(ALPHA, 10); + + clock.advance(Duration.ofDays(365)); + + assertThat(usage.viewScore(ALPHA)) + .as("an untimestamped legacy count is not silently decayed away") + .isEqualTo(10.0); + } + private void seedCount(String uri, long count) { Txn.executeWrite( assertions, @@ -174,4 +259,33 @@ private void seedCount(String uri, long count) { CortexNamespace.VIEW_COUNT, assertions.getDefaultModel().createTypedLiteral(count))); } + + /** A clock the test moves by hand, so decay can be observed without waiting for it. */ + private static final class MutableClock extends Clock { + + private Instant now; + + private MutableClock(Instant now) { + this.now = now; + } + + void advance(Duration amount) { + now = now.plus(amount); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + } } diff --git a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java index efcd4ba..9bc4262 100644 --- a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java +++ b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexAutoConfiguration.java @@ -292,12 +292,14 @@ Dataset inferences() { * shutdown does not discard them. * * @param assertions the assertions dataset, whose usage graph holds the counts + * @param properties the Cortex configuration properties, supplying the view half-life * @return the usage service */ @Bean(destroyMethod = "flush") @ConditionalOnMissingBean - UsageService usageService(@Qualifier("assertions") Dataset assertions) { - return new UsageService(assertions); + UsageService usageService( + @Qualifier("assertions") Dataset assertions, CortexProperties properties) { + return new UsageService(assertions, properties.search().viewHalfLife()); } /** diff --git a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java index d28cace..2e0f1eb 100644 --- a/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java +++ b/cortex-spring-boot-autoconfigure/src/main/java/ai/chatur/cortex/spring/CortexProperties.java @@ -20,6 +20,7 @@ * @param shapes the SHACL shapes ingested assertions are validated against, in Turtle syntax, * merged in order * @param rules the Jena rules used for inference, concatenated in order + * @param search the full-text search settings * @param web the web UI settings * @param mcp the MCP server settings * @param s3 the S3 client settings @@ -33,12 +34,29 @@ public record CortexProperties( @DefaultValue("classpath:ontology.ttl") List ontologies, @DefaultValue("classpath:ontology.shapes") List shapes, @DefaultValue("classpath:ontology.rules") List rules, + @DefaultValue Search search, @DefaultValue Web web, @DefaultValue Mcp mcp, @DefaultValue S3 s3, @DefaultValue Backup backup, @DefaultValue Restore restore) { + /** + * Settings for full-text search ranking. + * + *

Search results are ranked by textual relevance, then weighted by how often each resource has + * been deliberately opened, so a frequently consulted resource outranks an equally relevant one + * nobody reads. That weight is bounded, so popularity reorders comparable results rather than + * overriding relevance. + * + * @param viewHalfLife how long it takes a view's contribution to that weight to halve, so recent + * interest counts for more than interest that has since faded. Set to {@code 0} to disable + * decay entirely and weight by the raw lifetime view count instead — in which case a resource + * popular long ago outranks a newer one indefinitely. Changing this takes effect immediately; + * no stored history is rewritten. + */ + public record Search(@DefaultValue("30d") Duration viewHalfLife) {} + /** * Settings for the web UI auto-configured by {@link * ai.chatur.cortex.spring.web.CortexWebAutoConfiguration}. diff --git a/site/architecture.html b/site/architecture.html index 31dfca4..59b693f 100644 --- a/site/architecture.html +++ b/site/architecture.html @@ -112,6 +112,33 @@

Query, Ask, Describe, and Search all read the inference dataset, so results always include entailed statements.

+

How search ranks

+

Query text is tokenised by the same analyser that indexed the literals. That equality is + the whole game: Lucene resolves fuzzy terms without tokenising, so a query split by hand on + whitespace is looked up whole against an index the tokeniser already split differently, and + note-pad silently matches nothing while note pad + works. Labels and comments are separate fields, searched as separate branches so a name outranks + a description, and every term is required, so adding a word narrows rather than widens.

+

Textual relevance is then weighted by how often each resource is deliberately opened — + opening it, never merely appearing in a result list, which would boost whatever already ranked + highly and is self-fulfilling. Counts live in cortex://usage, a reserved named graph + beside provenance, so nothing here reaches the approved assertions. Views buffer in memory and + flush in batches: TDB2 admits a single writer, so a write per view would serialise reads against + ingestion.

+

The weight saturates and is bounded at 2×, and each view's contribution halves every + cortex.search.viewHalfLife. Both limits exist for + the same reason: popularity that compounds without bound becomes a rich-get-richer loop, since + boosted results are seen more and therefore opened more, and nothing new can break in. Bounding + the weight keeps popularity a tie-breaker between comparable results rather than a substitute for + relevance; decaying it means the ranking follows what people consult now rather than + whatever was popular once.

+
+ It is a ranking prior, not associative learning. Each resource carries one + decayed score of its own. Nothing strengthens a connection between two resources, so + despite the surface resemblance this is not Hebbian — there is no co-activation and no edge whose + weight changes. Storing a co-view score per pair would be. +
+

Modules & delivery mechanisms

The auto-configuration is grouped by how the graph is delivered — to the process, to humans, to agents, to durable storage, and seeded back from it — not by domain. That grouping is diff --git a/site/configuration.html b/site/configuration.html index 1f06faf..57c1db4 100644 --- a/site/configuration.html +++ b/site/configuration.html @@ -41,6 +41,7 @@

Core

cortex.ontologiesclasspath:ontology.ttlThe ontologies the graph is built on (Turtle), merged in order. cortex.shapesclasspath:ontology.shapesThe SHACL shapes ingested assertions are validated against, merged in order. cortex.rulesclasspath:ontology.rulesThe Jena rules used for inference, concatenated in order. + cortex.search.viewHalfLife30dHow long it takes a view's contribution to search ranking to halve. Results are ranked by textual relevance, then weighted by how often each resource has been deliberately opened. Set 0 to disable decay and weight by the raw lifetime count instead. The weight is bounded either way, so popularity reorders comparable results rather than overriding relevance. cortex.web.enabledtrueRegister the web UI controllers. Set false for the graph without the UI. cortex.mcp.enabledtrueRegister the MCP tools and resources. Set false for the graph without an MCP server.