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.
Douglas Adams gave us the long-running version in The Hitchhiker’s Guide to the Galaxy. Deep Thought spends seven and a half million years coming up with 42. Its clients are understandably disappointed. They wanted to know what life meant, and 42 is precious little help when nobody knows the Question. Deep Thought knows it can't work out the Question itself, but it can design a computer that can. That's how it ends up designing Earth. Ten million years is a long time to wait for a follow-up, particularly if you're one of the mice and the whole thing gets demolished five minutes early.
In the Show Me What You Got series we've been building Mostlylucid.Relevance, a C# framework for recommending candidates in a given context. It can work alongside the packing system: in the nail salon, Packing finds appointments that fit the available staff, stations and time, and Relevance ranks those options for the customer. This time we're looking at how Relevance learns which evidence to trust.
Alice wants gels around eleven on Friday. She needs a step-free station and usually sees Sarah. Packing can find a suitable slot at eleven with another qualified technician, or one a little later with Sarah. Which should the booking agent offer first? We could give Relevance two ranking heads: one ranks feasible appointments by how closely they match the requested time, the other by familiarity with the technician. Scheduling a nail salon
When a head receives feedback, Relevance multiplies its accumulated evidence by 0.99 before adding the new result. Suppose the salon extends its Friday hours and customers start favouring later slots with their usual technician. How many Fridays will it take before those choices outweigh the old evidence? I chose the 0.99. If the system can try a shorter memory and learn from subsequent appointments when to use it, it gets a say in that decision too.
What Relevance already learns
Part 1 gave behaviour coordinates and a moving centre. Part 1.5 used decision models to supply coordinates we couldn't measure directly. Part 2 used several representations to rank eligible candidates. Part 3 forecast where a journey was heading. Part 4 measured what happened when we intervened. Part 5 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 the average requested start time for Friday gels. |
| 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 salon's accumulated enquiries. 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
Suppose we want to estimate how late on Friday customers want appointments. Each enquiry gives us a requested start time in minutes after opening. One late request should move the estimate a little. A run of them should move it further. A moving average lets us choose how quickly that happens.
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.
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
Follow the signal from observation to outcome
Alice asking for eleven gives us a signal: a requested start time, supplied by the customer when she made the enquiry. A ranking head puts feasible slots in order using one representation of the request. A reward arrives later. If the objective is a completed treatment, the salon can record a positive outcome when Alice actually attends.
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.
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 the time head ranked Alice's slot first and technician familiarity ranked it second, they receive two-thirds and one-third of the credit. The next ranking in that placement uses this multiplier.
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. If Alice attends, both heads can receive credit even if she chose the slot because her sister could give her a lift. 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
Make the learner an entity
I want the same questions I can ask of a booking enquiry 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 ordinary Friday bookings and recover slowly after the opening hours change. 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
Signalrecord withKey,Value,Confidence,SourceandTimestamp. Its wave coordinator checksShouldRun, 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 · Wave coordinator - 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 · Pattern reputation
- 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 · DiSE image pipeline
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
On a busy Friday, enquiries and confirmed bookings usually rise together. Last Friday the salon had twenty more enquiries than usual and five fewer bookings. Was a gel technician off sick? Were the remaining slots all too late? I'd check the rota and the booking feed before changing a weight. Euclidean distance tells us how far the two counts moved. We also want to know how often they move in that direction together.
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
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:
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
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 client's reaction to an offer they never saw. Assignment and outcome handling
Apprenticeship meets automated A/B testing
Alice has already booked. Now the manager wants to know whether offering an easy way to reschedule in the appointment reminder helps more clients attend. The control gets the usual reminder. The challenger gets the same message at the same time with a rescheduling link. Pick the outcome before the first send. Here I'd count whether the treatment took place within seven days of its original date, including clients who used the link to move it.
During apprenticeship the manager reviews the message, checks who is eligible and tries the rescheduling link. Once approved, the service randomly assigns eligible clients to the two versions and records which one each received or was due to receive. Keep everyone in their assigned group, even if delivery failed or they never opened the reminder. After the seven-day window, compare attendance rates and check whether the change increased opt-outs.
What crosses the async boundary?
In a .NET service, assignment and feedback usually belong to different handlers. The attendance event 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.
// Assignment handler. Reuse this request on a transport retry.
var request = new InterventionRequest(
Id: "appointment-42/reminder-trial",
Unit: "appointment-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 the salon records a completed treatment inside the measurement window, the outcome handler uses the decision ID retained with that assignment.
var outcome = new InterventionEvent(
Id: "appointment-42/completed",
Decision: decisionId,
Stage: "outcome",
At: completedAt,
Source: "salon-diary",
Reward: 1,
Outcome: "treatment-completed");
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 completed treatment can yield a zero. If the attendance 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
What earns promotion?
For a worked example, suppose 100 of 1,000 clients assigned to the usual reminder complete their treatment within the window, 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 opt-out 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 · DiSE: Graduated Apprenticeships
What would we learn about running the nail salon?
So far the booking agent has offered Alice an appointment and the salon has observed whether she came in. The manager has another use for those observations. She needs to decide who should work next Friday and what they'll need in the stock cupboard.
For that forecast, keep the enquiries the salon couldn't accommodate. If both Friday mornings filled up, the appointment book alone can't tell the manager that she turned away one gel client the first week and eight the next.
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.
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 completed treatments and cancellations. A reminder can attract plenty of clicks from clients trying to cancel.
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.
Open the learning lab. 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 and the intervention lab. 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 salon extends its Friday hours. On a quiet Tuesday, though, three bookings 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 appointment each version would have offered. Then use a controlled trial to find out whether switching helped. The selector can go through the same apprenticeship as the rules it chooses.