# SHOW ME WHAT YOU GOT (Part 6): Recursive Self-Improvement from the Ground Up

There's a lot of interest in recursive self-improvement (RSI) in AI development. A system improves the procedure it learns with, then uses the revised procedure the next time it learns. A model that helps design the training procedure for its successor is one example. We can try the same idea with the recommender from Part 2.

Part 2 ranked products using several sources of evidence, including category and price. Each has its own ranking head. When a head receives feedback, Relevance multiplies its accumulated evidence by `0.99` before adding the new result. Relevance learns how much weight to give price. I chose the `0.99`.

Suppose the shop switches to its autumn range and recommendations take a week to catch up. Would a head that forgot old results faster have ranked the new stock better? We can keep both versions running and record where their rankings differ. If Relevance can use subsequent outcomes to choose which rule updates its weights, it's learning how quickly to learn.

<datetime class="hidden">2026-11-28T12:00</datetime>
<!-- category -- AI,Architecture,Machine Learning,Recommendations,Behavioural Inference,C#,StyloBot,DiSE -->

[TOC]

## What Relevance already learns

[Part 1](/blog/show-me-what-you-got-streaming-recommendations) gave behaviour coordinates and a moving centre. [Part 1.5](/blog/show-me-what-you-got-part1-5-questions-as-coordinates) used decision models to supply coordinates we couldn't measure directly. [Part 2](/blog/show-me-what-you-got-part2-building-relevance) used several representations to rank eligible candidates. [Part 3](/blog/show-me-what-you-got-part3-predict) forecast where a journey was heading. [Part 4](/blog/show-me-what-you-got-part4-mind-control) measured what happened when we intervened. [Part 5](/blog/show-me-what-you-got-part5-please-change-this) brought those pieces together in the package.

We can now ask what changes when feedback arrives.

| Loop | What changes | Relevance example |
| --- | --- | --- |
| Adaptation | The representation of an entity | A new observation moves a shopping session's centroid. |
| Optimisation | A parameter used to make decisions | An observed outcome changes the influence of a ranking head. |
| Meta-learning | The rule that learns those parameters | Compare ways to update head weights and promote one on measured performance. |

Think about what you'd persist after a restart. The first loop needs the shopper's accumulated observations. The second also needs the evidence for each head's weight. The third needs the history of which updater was in charge and what happened under its watch.

The first two run in the code today. The third is the extension we'll design here. I'll call the loop recursive when the improvement policy itself is measured and can be replaced through the same evaluation process. There can be a fixed limit on what it can change, how often it can change it, and how much that process costs.

## Start with one moving number

Say a shopper spends five minutes comparing tents, then starts looking for a stove. We want the representation to move toward the new evidence. We also want a single stray click to have limited influence. A moving average gives us a knob for that trade-off.

```csharp
estimate += alpha * (observation - estimate);
```

This one-coordinate teaching example moves the estimate by a fraction of the error. With a constant target and `alpha = 0.2`, 80% of the old error survives each update. After ten updates, about 11% survives. With a noisy target, a high gain also carries more of the noise into the estimate. If we allow gains above one, the estimate can overshoot. At two, a constant target produces an error of equal magnitude and opposite sign every step. Above two it grows.

Relevance's implementation accounts for **elapsed time** and **event weight**. Here is the decay function from `RelevanceEngine`.

```csharp
private double Decay(TimeSpan elapsed) => Math.Pow(0.5, Math.Max(0, elapsed.TotalMinutes) / definition.HalfLifeMinutes);
```

For each point, the engine multiplies both its accumulated vector sum and its evidence mass by that factor. Then it adds the new vector multiplied by the event weight, and adds the weight to the mass. It reads the centroid as sum divided by mass. An idle session keeps the same centre while its evidence weakens. The next event therefore has more pull, and a session with too little mass can fall back to eligible defaults. In the scalar teaching equation the effective gain would be the new event's weight divided by the new total mass.

Event time and feedback count are different clocks. A half-life of ten minutes halves the stored mass over ten idle minutes. The head feedback factor of `0.99` takes about 69 updates to that head to halve its old evidence. A busy placement can reach that point in an hour and a quiet one in a month. That difference is a useful question to ask of a learner before changing it. [RelevanceEngine.cs](https://github.com/scottgal/mostlylucidweb/blob/main/Mostlylucid.Relevance/RelevanceEngine.cs)

## Follow the signal from observation to outcome

A **signal** is a piece of evidence with a meaning, a source and a point in time. A price comparison can become a measured coordinate. A ranking **head** is an opinion produced from a configured point representation, such as category or price. A **reward** says how an exposed decision turned out according to a particular objective. Those three things have different jobs.

In Relevance, point converters produce vectors and the engine runs one neighbour query per eligible head with enough evidence. It combines the ranked lists using weighted reciprocal rank fusion. A contribution at rank `r` adds `weight / (k + r)` to the item's fused score, where `k` controls how steeply the contribution falls with rank. A feedback event names a retained recommendation and a returned candidate. The engine checks that the reward is in [0, 1] and deduplicates outcomes for that decision and item. Its update uses the reasons recorded at decision time.

```csharp
var credit = (1.0 / reason.Rank) / total;
evidence.Positive = 0.99 * evidence.Positive + reward * credit;
evidence.Negative = 0.99 * evidence.Negative + (1 - reward) * credit;
```

Here `total` is the sum of reciprocal ranks for the heads that supported the item. If category put the item first and price put it second, they receive two-thirds and one-third of the credit. The next ranking in that placement uses this multiplier.

```csharp
var weight = baseWeight * (0.5 + (1 + evidence.Positive) / (2 + evidence.Positive + evidence.Negative));
```

The multiplier starts at 1 and stays between 0.5 and 1.5. The added counts smooth early feedback. A shopper buying the item gives both heads some credit, even if a discount did all the work. Treat the credit as a rule for distributing an observed reward. Estimating each head's incremental effect requires a comparison in which its contribution actually varies. [Recommendation and feedback paths](https://github.com/scottgal/mostlylucidweb/blob/main/Mostlylucid.Relevance/RelevanceEngine.cs)

## Make the learner an entity

I want the same questions I can ask of a shopping session to work on a learning component. Where is it now? How did it get here? What else behaves like it? When did it change?

The unit I would characterise is a **versioned strategy in a given context**. A long-memory learner might do well on steady catalogue traffic and recover slowly when stock changes. Averaging its performance across both contexts would hide the reason to keep it around.

| Signal about the learner | What I'd record |
| --- | --- |
| Usefulness | Reward over a named horizon and lift against a concurrent control |
| Support | Completed outcomes, outstanding assignments and censored observations |
| Recovery | Error following a known change and time to recover |
| Redundancy | Overlap with another head and lift when one is removed under an experiment |
| Cost | Latency distribution, CPU time and calls to expensive models |
| Stability | Weight movement, policy switches and the volume of evidence behind each |

Keep the original outcome records alongside these summaries. Each assignment needs its ID, context, strategy version, eligible alternatives and recorded assignment probability. Execution signals should capture what actually ran and what it cost. Outcome signals should identify their source, horizon and completion status. A missing observation deserves its own state. Otherwise a failed measurement can silently become a negative reward.

This builds on a pattern I've used elsewhere:

- **StyloFlow** has a retrieval `Signal` record with `Key`, `Value`, `Confidence`, `Source` and `Timestamp`. Its wave coordinator checks `ShouldRun`, executes eligible waves and adds their output to the analysis context. This gives downstream work access to named evidence and its origin. To evaluate the scheduling policy itself, I'd also retain why a wave ran or was skipped, its cost and a downstream quality result. [Signal contract](https://github.com/scottgal/styloflow/blob/main/src/StyloFlow.Retrieval.Core/Analysis/Signal.cs) · [Wave coordinator](https://github.com/scottgal/styloflow/blob/main/src/StyloFlow.Retrieval.Core/Orchestration/WaveCoordinator.cs)
- **Stylo.Bot** publishes typed learning signals for user feedback, client-side validation, model updates and fast-path drift. Its pattern reputation updater weights evidence in an online moving average and has a separate eligibility check for pattern types that can lead to a learned block. That distinction matters when some observations arrive from adversarial traffic. A validated label, a detector's prediction and an external observation should retain their provenance all the way through evaluation. [Learning signal keys](https://github.com/scottgal/stylobot/blob/main/src/Mostlylucid.BotDetection/Learning/LearningSignalKeys.cs) · [Pattern reputation](https://github.com/scottgal/stylobot/blob/main/src/Mostlylucid.BotDetection/Data/PatternReputation.cs)
- **DiSE** gives the expensive path a second job as a source of supervision. In the graduated apprenticeship design, a workflow begins under close checking, graduates to sampled oversight as it earns trust, and can be checked more closely when quality falls. In the image pipeline, deterministic waves and model-proposed signals feed a shared ledger whose evidence can be inspected. [Graduated Apprenticeships](/blog/blog-article-cooking-dise-part2-apprenticeships) · [DiSE image pipeline](/blog/constrained-fuzzy-image-intelligence)

A producer's confidence, its measured reliability and its current influence on a decision should be stored separately. A highly confident signal can be redundant. A cheap signal with modest accuracy can add useful information after the other contributors have spoken.

## Tell drift from ordinary variation

If clicks and basket additions rise together every weekend, a two-coordinate jump can be perfectly ordinary. A smaller change in which clicks rise and basket additions fall might be worth investigating. Euclidean distance measures the length of both moves. To tell which one is unusual, we need to know how the coordinates usually move together.

Imagine a typical weekend adds 100 clicks and 10 baskets. This weekend we see 100 extra clicks and *lose* 10 baskets. Looking at the two counters separately, neither change in magnitude seems remarkable. What changed is their relationship. I'd first check whether checkout telemetry was still arriving before letting any learner adjust its weights.

Covariance describes that joint movement. Given a baseline centre `mean` and covariance matrix `S`, squared Mahalanobis distance is `(x - mean)ᵀ S⁻¹ (x - mean)`. A move along a direction with lots of normal variation counts less than the same move along a quiet direction. In code I'd solve a linear system against a regularised covariance matrix, then take the dot product, rather than compute a matrix inverse. Early on, or with near-duplicate features, shrink toward a diagonal estimate and require enough observations before trusting the joint estimate.

The same calculation can flag a strange combination of learner signals, such as rising cost alongside falling lift. A distance tells us where to investigate. A concurrent control or fresh adjudication helps explain whether the learner degraded, the incoming population changed, or the measurement broke. Keep a reference window as well as recent summaries, otherwise slow drift can move the baseline along with it.

Sometimes there are several kinds of normal. A centroid gives each known group a compact centre. If neighbourhoods have irregular shapes, build a sparse graph from similar context windows and use Leiden community detection to propose groups. Once we find a group, we can check whether it turns up again the following week and whether the same strategy still works well for it. Relevance's intervention learner already keeps bounded nearest-centre context groups. The covariance and graph methods here are possible extensions. [Intervention learning](https://github.com/scottgal/mostlylucidweb/blob/main/Mostlylucid.Relevance.Learning/InterventionLearning.cs)

## Learn online and keep a comparison

The more feedback we collect, the more expensive it gets to refit from every event. For a small linear model we can keep running sums that contain the information the fit needs. Relevance's learning package does this per context group. From `ContextGroup.Learn`, where `x` is the intervention descriptor with an intercept prepended:

```csharp
for (var i = 0; i < x.Length; i++)
{
    Target[i] += x[i] * reward;
    for (var j = 0; j < x.Length; j++) Gram[i][j] += x[i] * x[j];
}
```

The Gram matrix accumulates feature co-occurrences. The target vector accumulates feature–reward products. Ridge regression adds a diagonal penalty before solving for coefficients, helping when descriptors are correlated or there is little evidence. Memory for those statistics is quadratic in descriptor width and independent of the number of completed outcomes. The learner updates on a reported outcome and computes scores at assignment time. Those operations can run minutes or days apart. These sums in the current implementation accumulate without decay. [OnlineModels.cs](https://github.com/scottgal/mostlylucidweb/blob/main/Mostlylucid.Relevance.Learning/OnlineModels.cs)

The intervention learner also records how a choice was made. During uniform assignment each eligible variant has probability `1 / N`. In its epsilon-greedy mode the best-scoring variant receives probability `1 - epsilon + epsilon / N`, while each alternative gets `epsilon / N`. The logged probability belongs to the choice on that assignment, with the eligible set at that moment. This is an existing example of a contextual bandit: each choice is an arm, the context informs its estimated value, and exploration buys information at the cost of occasionally passing up the current favourite.

**Regret** measures reward forgone against a specified comparator. In a simulator we can know the best arm's expected reward at each step. In production we can estimate differences from a controlled comparison. Given logged assignment probabilities and overlap, inverse-propensity weighting can estimate another policy's value over actions with support. Rare choices get large weights and can make the estimate noisy. When a policy never tried an action in a context, those logs alone cannot tell us what would have happened there.

Part 4's distinction between assignment, application, view and outcome matters here. An email that was assigned and never opened still belongs to the assigned group. A missing outcome window is a different case again. Preserve both the assigned cohort and the completion counts. For head-level credit, use ablation under controlled assignment when you need incremental lift. Shadow ranking can compare candidate order and compute cost on the same requests. It cannot give a shopper's reaction to an offer they never saw. [Assignment and outcome handling](https://github.com/scottgal/mostlylucidweb/blob/main/Mostlylucid.Relevance.Learning/InterventionLearning.cs)

## Apprenticeship meets automated A/B testing

Suppose the intervention is a reminder for shoppers who left something in their basket. The workflow proposes a shorter email and a different delivery time. We can test the whole change as one variant, or vary the copy and timing independently if we have enough traffic to learn which part matters. Either way, decide what counts as success before sending anything. For this example I'd measure completed orders within a fixed horizon and track unsubscribes as a constraint.

The apprenticeship starts under supervision. A reviewer checks the proposed message, who can receive it and whether the experiment can actually measure the intended outcome. Once the variants are approved, the software can run the A/B test: assign eligible shoppers to the existing policy or the new nudge, record the version and assignment probability, and wait for the outcome window to close. Count outcomes by assigned group, including people who never open the email. If the question is whether to send a reminder at all, make the control a no-send group. Opening the message tells us it reached someone. The difference in completed orders between assigned groups estimates what the nudge changed.

### What crosses the async boundary?

In a .NET service, assignment and feedback usually belong to different handlers. The checkout consumer might run on another instance long after the email worker has finished. The durable join between them is the decision ID. Here's the shape of the two calls using the existing learning API. Assume the control and challenger are registered, and the two coordinates have the meanings configured for this experiment.

```csharp
// Assignment handler. Reuse this request on a transport retry.
var request = new InterventionRequest(
    Id: "basket-42/reminder-trial",
    Unit: "basket-42",
    Coordinates: [0.7, 0.8],
    ObservedAt: observedAt,
    Randomised: true);
var decision = await learning.ChooseAsync(request);
// Carry decision.Id and decision.Variant.Id into the delivery record.
```

`Randomised: true` gives both eligible variants an equal chance in this two-arm trial. The application delivers the assigned variant. Later, when checkout confirms an order inside the measurement window, the outcome handler uses the decision ID retained with that assignment.

```csharp
var outcome = new InterventionEvent(
    Id: "order-893/completed",
    Decision: decisionId,
    Stage: "outcome",
    At: purchasedAt,
    Source: "checkout",
    Reward: 1,
    Outcome: "purchase");
await learning.SaveAsync(outcome);
```

Consider what happens if the consumer saves the outcome and crashes before acknowledging its message. On redelivery, the same event ID and payload count once. The package tests exercise that retry and reject conflicting rewards. A verified observation window with no order can yield a zero. If the checkout feed went down, mark the observation as censored. Treating an outage as a run of unsuccessful nudges would teach the updater to distrust whichever variant happened to be running. [Intervention learning tests](https://github.com/scottgal/mostlylucidweb/blob/main/Mostlylucid.Relevance.Tests/InterventionLearningTests.cs)

### What earns promotion?

Suppose 100 of 1,000 shoppers assigned to the existing reminder order, compared with 112 of 1,000 assigned to the new one. The observed lift is 1.2 percentage points. Under independent random assignment, a rough 95% interval for that difference runs from −1.5 to +3.9 points. A dashboard can put the challenger in first place while the trial still leaves room for it to be worse. Decide the sample size or sequential stopping rule before automating promotion.

The same experiment supplies evidence for two decisions.

| Decision | Evidence |
| --- | --- |
| Should this nudge graduate from trial to routine use? | Measured lift against the control, with enough completed assignments and acceptable unsubscribe rates. |
| Has the workflow earned lighter supervision for similar trials? | A history of sound proposals, valid assignments, reliable outcome collection and acceptable results across several experiments. |

Even a conclusive trial tells us about one nudge in one population. Deciding how much review the workflow needs takes evidence across trials. As the workflow earns trust, it can move from approval of every proposal to sampled review within the same eligibility and contact rules. Keep a control wherever we still need to measure incremental effect. If lift drops, outcome collection fails or the audience changes, increase the review rate again.

This is where the learner becomes measurable. Log the proposal version, assignment, delivery, outcome and review decision as distinct signals. Then the apprenticeship policy itself can be a challenger. Compare two review schedules across independent trials and ask whether one saves reviewer time while maintaining experiment quality and downstream outcomes. Relevance already supplies assignment and outcome tracking for the nudge. Connecting those results to graduation and renewed supervision is the proposed extension. [Part 4: Experimenting with behavioural nudges](/blog/show-me-what-you-got-part4-mind-control) · [DiSE: Graduated Apprenticeships](/blog/blog-article-cooking-dise-part2-apprenticeships)

## What would we learn about running the nail salon?

In the packing series, Alice asks The Nail Room for gels around eleven on Friday. She needs a step-free station and usually sees Sarah. The scheduler can find appointments that fit the treatment, the technician and the station, including time to reset it for the next customer. Suppose it finds two. Which one should the booking agent suggest first? [The nail salon packing example](/blog/packing-algorithms-in-csharp-part-2)

We could try offering Alice the time closest to eleven, or a slightly later appointment with Sarah. Both must meet her access requirements. Across comparable enquiries, the automated A/B test could tell us whether offering the familiar technician first leads to more **completed appointments**. Record what we offered, what the customer chose and whether they came in. Also record enquiries we couldn't accommodate. If Friday mornings always sell out, the calendar alone makes a busy morning and an overwhelmed one look exactly alike.

On Monday the manager needs next week's rota. If recent enquiries point to more Friday gels and fewer pedicures, the system could suggest moving a gel-qualified technician's hours to Friday morning. The same forecast could suggest how much base coat to order, using expected treatments, typical usage, stock on hand and the supplier's lead time. Did we turn fewer people away? Did we pay for hours that went unused? Did the base coat arrive before we ran out?

We're learning how to run the salon. The bookings inform the rota and the stock order. In turn, the rota and the stock cupboard determine which appointments we can offer. I'd start the apprenticeship with the manager reviewing those suggestions and recording why they changed one. For the recursive step, compare two ways of learning Friday demand: one gives recent enquiries more weight, the other relies more heavily on the same weekday over several weeks. Score their forecasts against later enquiries, then test whether using the better forecast actually helps the manager plan. For a rota I'd compare whole weeks, since customers on the same Friday share the same staff. These are proposed uses of Relevance alongside the salon scheduler.

## Put a limit on the recursion

Start with the current feedback updater as the champion. Give a challenger a different memory rule, perhaps a shorter half-life after a measured regime change. Score both on chronological replay for stability and cost. Then put eligible challengers into a small, concurrent, randomised trial. Keep the same objective, eligibility checks and outcome horizon. Judge results after outcomes have matured and require enough support to justify the switch.

```mermaid
flowchart LR
    O[Observations] --> R[Representation]
    R --> D[Decision and strategy version]
    D --> F[Outcome and compute signals]
    F --> R
    F --> W[Weight update]
    W --> D
    F --> E[Evaluate learning strategies]
    E --> P[Promote a version or retain champion]
    P --> W
    P --> M[Measure the promotion policy]
    M --> E
```

The last loop measures the **selector** as well. Does switching more quickly improve recovery enough to pay for extra experiments? Does widening the challenger pool help, or just increase the chance that one gets lucky? Compare selector versions over independent episodes with a fixed evaluation budget. Freeze the objective, the promotion authority and the constraints outside that loop. Keep versioned state, preserve a warm champion where feasible and have an explicit rollback path. Two interacting loops can amplify each other's noise, so give the slower one enough time to see the consequences of its last update.

The same loop can learn where to spend compute. Start with the cheap path. Measure a more expensive head on a controlled sample, including some cases where the cheap path looks confident. Estimate its marginal improvement in each eligible context. Compare that with CPU, latency and model-call cost, and enforce hard resource limits before choosing. An expensive wave that improves results near a decision boundary may be worth keeping there even if running it everywhere loses money.

A recommender's exposures shape its future evidence. A detector's enforcement can censor outcomes and its inputs can be adversarial. In both cases we need independent checks, versioned decisions and a way to distinguish the source of a label. For defensive deployments, promotion should rely on trusted evidence and fixed policy constraints. For recommendations, measure the outcome you actually want, including returns or failures if they matter. Optimising clicks alone can reward a system for showing things people regret buying.

## Try the loops on the same stream

The lab below uses reproducible synthetic evidence. The first view shows a fixed estimate next to a moving one. Try **Steady target** with a gain of `0.15`, then `2.05`. In **Step change**, compare a slow and a fast gain. The dotted line is the underlying target the simulator knows. Real systems need evidence to estimate it.

The second view compares equal fixed weights, fixed evidence updates, and a controller that chooses between two evidence memories. Each adaptive candidate receives the same delayed feedback for both heads. At each step the controller chooses using errors from outcomes that have already arrived. The simulator can expose both rewards for teaching purposes. A recommendation experiment must account for what its policy actually showed.

<iframe class="article-explainer" src="/interactive/explainers/learning.html" title="Interactive replay of learning rates and signal weights" loading="lazy" width="100%" height="660"></iframe>

<a href="/interactive/explainers/learning.html" hx-boost="false">Open the learning lab</a>. Switch to **Drift**, increase the feedback delay and shorten the evaluation window. Watch the selected memory alongside the weight traces. A short window can mistake noise for a better learner. A long delay can leave both learners adapting to a regime that's already gone. The chart's cumulative regret uses the simulator's expected reward gap, so early lucky outcomes do not masquerade as improvements.

To run this experiment on Relevance itself, start with the [package sample](https://github.com/scottgal/mostlylucidweb/tree/main/samples/RelevancePackage) and the [intervention lab](https://github.com/scottgal/mostlylucidweb/tree/main/samples/RelevanceLearning). Log the head contributions and decision IDs already available in the ranking result. Replay four configurations over the same chronological stream: frozen representation and weights, moving representation with fixed weights, feedback-adjusted weights, and feedback-adjusted weights with a selectable update rule. Compare later windows and keep feedback arrival times separate from assignment times. Add the versioned evaluator around those runs before putting any challenger into live traffic. The browser lab demonstrates the update rules in isolation. This four-way package experiment is the next implementation step.

## Learning to learn

Suppose the shorter-memory updater catches up two days sooner after the autumn stock change. On a quiet Tuesday, though, three purchases are enough to send its weights all over the place. There's a reason to keep both versions.

I'd check the first Tuesday the selector picked the faster updater. What evidence did it have that morning? Keep the rankings from both versions so we can see which appointments or products would have been offered differently. Then use a controlled trial to find out whether switching helped. The selector can go through the same apprenticeship as the rules it chooses.
