Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 40 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -184,6 +184,36 @@ 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 + 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.
Expand Down Expand Up @@ -255,5 +285,9 @@ 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.
- 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
prior runs with persistence on. Safe to delete when no process holds `db/tdb.lock`.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
30 changes: 29 additions & 1 deletion cortex-core/src/main/java/ai/chatur/cortex/CortexBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
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.time.Duration;
import java.util.List;
import org.apache.jena.ontapi.model.OntModel;
import org.apache.jena.query.Dataset;
Expand Down Expand Up @@ -47,10 +49,19 @@
*/
public final class CortexBuilder {

/**
* The default half-life of a view's contribution to search ranking.
*
* <p>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<String> ontologies = List.of();
private List<String> shapes = List.of();
private List<String> rules = List.of();
private String assertionsLocation;
private Duration viewHalfLife = DEFAULT_VIEW_HALF_LIFE;

private CortexBuilder() {}

Expand Down Expand Up @@ -111,6 +122,22 @@ public CortexBuilder persistent(String assertionsLocation) {
return this;
}

/**
* Sets how long it takes a view's contribution to search ranking to halve.
*
* <p>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.
*
Expand Down Expand Up @@ -139,7 +166,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, viewHalfLife);
QueryService queryService = new QueryService(inferences, assertions, ontModel, usageService);
StatsService statsService =
new StatsService(assertions, inferences, ontModel, parsedShapes, parsedRules);

Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -13,6 +14,26 @@ 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.
*
* <p>Like {@link #PROVENANCE} this is a reserved graph, not a branch and not part of the approved
* assertions: it records how the graph is <em>used</em> rather than what it claims.
*/
public static final Resource USAGE = ResourceFactory.createResource(NS + "usage");

/**
* The property recording a resource's time-decayed view score, within {@link #USAGE}.
*
* <p>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() {}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -98,18 +100,22 @@ ORDER BY DESC(?score)
private final Dataset inferences;
private final Dataset assertions;
private final OntModel ontModel;
private final UsageService usageService;

/**
* Creates the service.
*
* @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;
}

/**
Expand Down Expand Up @@ -184,6 +190,9 @@ List<Term> listInstances(OntClass ontClass) {
* @return the statements about the resource, sorted by predicate
*/
public List<ProvenancedStatement> 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<StatementKey, String> created = getCreated(subject);
List<ProvenancedStatement> statements = new ArrayList<>();
Expand Down Expand Up @@ -297,7 +306,30 @@ public List<SearchResult> 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.
*
* <p>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<SearchResult> rankByPopularity(Map<String, SearchResult> best) {
Map<String, Double> 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);
}

/**
Expand All @@ -306,8 +338,8 @@ public List<SearchResult> searchSubjects(String text) {
* <p>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.
*
* <p>Every token is required, so adding a word narrows the result set rather than widening it.
*/
Expand Down Expand Up @@ -351,7 +383,7 @@ private static List<String> analyze(String text) {
* Grades edit distance by token length.
*
* <p>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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 <em>not</em> 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
*/
Expand Down
Loading
Loading