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
4 changes: 2 additions & 2 deletions release/upgrade-support.json

Large diffs are not rendered by default.

30 changes: 26 additions & 4 deletions src/powercontext/builtin/persistence/experience_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ async def search_approved_artifact_rows(
"result_limit": limit,
"required": min(required, len(terms) + 1),
}
projection_admitted = "0"
if connection.dialect.name == "sqlite":
coverage, values = sqlite_fts_coverage_sql(terms) if required > 1 else ("1", {})
parameters["query"] = fts_match_query(query)
Expand All @@ -392,6 +393,13 @@ async def search_approved_artifact_rows(
)
identity = "f.rowid AS projection_id, "
projection_join = "JOIN pc_artifact_fts AS p ON p.rowid=c.projection_id "
if family == Experience.family:
# Reuse admission only when the FTS copy agrees with the exact head's projection.
projection_admitted = (
"EXISTS (SELECT 1 FROM pc_artifact_heads AS head "
"WHERE head.scope_id=:scope_id AND head.family=:family AND head.artifact_id=c.artifact_id "
"AND head.revision=c.revision AND head.searchable_text=p.searchable_text)"
)
else:
coverage, values = oceanbase_fts_coverage_sql(terms) if required > 1 else ("1", {})
parameters["query"] = analyze_fts_query(query)
Expand All @@ -403,6 +411,13 @@ async def search_approved_artifact_rows(
"JOIN pc_artifact_heads AS p ON p.scope_id=:scope_id AND p.family=:family "
"AND p.artifact_id=c.artifact_id AND p.revision=c.revision "
)
if family == Experience.family:
projection_admitted = "1"
if required == 1:
# MATCH alone does not prove exact term coverage on this path.
exact_coverage, exact_values = oceanbase_fts_coverage_sql(terms)
parameters.update(exact_values)
projection_admitted = f"{exact_coverage.replace('searchable_text', 'p.searchable_text')} >= :required"
parameters.update(values)
eligibility = f"WHERE h.scope_id=:scope_id AND h.family=:family AND h.lifecycle_state='active' AND {predicate}"
matches = f"FROM {source} {eligibility}"
Expand All @@ -428,7 +443,10 @@ async def search_approved_artifact_rows(
else ()
)
if len(qualified) >= limit or len(observed) < parameters["probe_limit"]:
return witness + tuple({**row, "family": family, "score_metric": metric} for row in qualified[:limit])
return witness + tuple(
{**row, "family": family, "score_metric": metric, "projection_admitted": family == Experience.family}
for row in qualified[:limit]
)
prefix = ""
candidate_source = source
if connection.dialect.name == "sqlite" and required > 1:
Expand Down Expand Up @@ -461,7 +479,7 @@ async def search_approved_artifact_rows(
)
rejected = (
(
" UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1 FROM "
" UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 1 FROM "
"(SELECT 1 WHERE (SELECT COUNT(*) FROM raw_probe) > "
"(SELECT COUNT(*) FROM qualified_probe)) AS rejected"
)
Expand All @@ -472,7 +490,8 @@ async def search_approved_artifact_rows(
f"WITH {prefix}candidates AS ({candidates}) " # noqa: S608
"SELECT c.artifact_id AS artifact_id, c.revision AS revision, p.searchable_text AS searchable_text, "
"a.content, a.created_at, a.created_by, a.restored_from_revision, a.rollback_reason, "
f"c.raw_score AS raw_score, 0 AS is_rejected FROM candidates AS c {projection_join}"
f"c.raw_score AS raw_score, {projection_admitted} AS projection_admitted, 0 AS is_rejected "
f"FROM candidates AS c {projection_join}"
"LEFT JOIN pc_artifacts AS a ON a.scope_id=:scope_id AND a.family=:family "
f"AND a.artifact_id=c.artifact_id AND a.revision=c.revision{rejected} "
f"ORDER BY is_rejected DESC, raw_score {direction}, artifact_id, revision"
Expand All @@ -497,6 +516,7 @@ def experience_search_hits(

``admission=None`` applies the historical lexical floor bit for bit. Raw score metadata
is optional for old custom indexes; public searches set ``require_scores=True``.
Rows qualified by the built-in projection can reuse that admission during decoding.

``retrieved`` counts the rows *examined*, not the rows kept: the loop stops as soon as
``limit`` final hits survive, so a backend that returned many rows for a narrow query is
Expand All @@ -522,7 +542,9 @@ def experience_search_hits(
),
)
content = _content(row["content"])
if not admits_fts_text(query, experience_search_text(content), floor=admission):
if not row.get("projection_admitted") and not admits_fts_text(
query, experience_search_text(content), floor=admission
):
continue
admitted += 1
retrieval_score, channel_scores = _search_scores(row, required=require_scores or min_score is not None)
Expand Down
27 changes: 27 additions & 0 deletions src/powercontext/builtin/persistence/recurrence.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,33 @@ async def observations_for_target(
).mappings()
return tuple(_decode_observation(row) for row in rows)

async def verdicts_for_target(
self,
connection: AsyncConnection,
scope_id: str,
artifact_ref: ArtifactRef,
signature_key: str,
/,
) -> tuple[RecurrenceObservation, ...]:
"""Return the ``recurred`` and ``avoided`` events of one bucket in journal order."""

scope = validate_scope_id(scope_id)
_require_normalized_key(signature_key)
rows = (
await connection.execute(
select(RECURRENCE_OBSERVATION_TABLE)
.where(
*_bucket_conditions(scope, artifact_ref, signature_key),
RECURRENCE_OBSERVATION_TABLE.c.event != "selected",
)
.order_by(
RECURRENCE_OBSERVATION_TABLE.c.task_outcome_position,
RECURRENCE_OBSERVATION_TABLE.c.observation_id,
)
)
).mappings()
return tuple(_decode_observation(row) for row in rows)

async def event_counts_for_target(
self,
connection: AsyncConnection,
Expand Down
68 changes: 39 additions & 29 deletions src/powercontext/builtin/runtime/recurrence.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from __future__ import annotations

from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any

Expand Down Expand Up @@ -115,13 +116,22 @@ async def record_window(
"""Record every event one incubation window proves, in evidence order."""

outcomes = tuple((row, outcome) for row in rows if (outcome := _task_outcome(row)) is not None)
if not outcomes:
return ()
# Every unlinked outcome matches against the same scope-head snapshot, and
# this method writes no artifacts, so read the snapshot once per window.
needs_heads = any(outcome.handoff_receipt_ref is None for _, outcome in outcomes)
heads: _Contents = await self._experience_heads(connection) if needs_heads else ()
# this method writes no artifacts, so read the snapshot at most once per window
# when an unrecorded failure item with available evidence actually needs it.
heads: _Contents | None = None

async def scope_heads() -> _Contents:
nonlocal heads
if heads is None:
heads = await self._experience_heads(connection)
return heads

proposals: list[RecurrenceRevisionProposal] = []
for row, outcome in outcomes:
proposals.extend(await self._record_outcome(connection, row, outcome, heads=heads))
proposals.extend(await self._record_outcome(connection, row, outcome, scope_heads=scope_heads))
return tuple(proposals)

async def effectiveness(
Expand Down Expand Up @@ -163,20 +173,20 @@ async def _record_outcome(
outcome: TaskOutcome,
/,
*,
heads: _Contents,
scope_heads: Callable[[], Awaitable[_Contents]],
) -> tuple[RecurrenceRevisionProposal, ...]:
link = await self._resolve_link(connection, outcome)
if not isinstance(link, (_LinkedHandoff, type(None))):
return ()
contents: _Contents = () if link is None else link.contents
if link is not None:
await self._record_selected(connection, row=row, link=link, contents=contents)
candidates: _Contents = contents if link is not None else heads
matches = await self._freeze_matches(
connection,
row=row,
outcome=outcome,
contents=candidates,
contents=None if link is None else contents,
load_contents=scope_heads if link is None else None,
mode="handoff_citations" if link is not None else "scope_heads",
)
if link is not None:
Expand Down Expand Up @@ -309,29 +319,32 @@ async def _revision_proposal(
in statistics and proposes nothing.
"""

content = await self._experience_content(connection, artifact_ref)
if content is None or content.failure is None:
try:
target = await self.artifacts.get(connection, self.scope_id, artifact_ref)
except RepositoryNotFoundError:
return None
if not isinstance(target.content, ExperienceContent) or target.content.failure is None:
return None
content = target.content
if content.failure.repair_surface != _EXPERIENCE_CONTENT_SURFACE:
return None
try:
current = await self.artifacts.latest(
connection,
self.scope_id,
artifact_ref.family,
artifact_ref.artifact_id,
known=target,
)
except RepositoryNotFoundError:
return None
if current.as_ref() != artifact_ref:
return None
if content.failure.repair_surface != _EXPERIENCE_CONTENT_SURFACE:
return None
observations = await self.recurrence.observations(connection, self.scope_id)
verdicts = tuple(
observation
for observation in observations
if observation.artifact_ref == artifact_ref
and observation.signature_key == cue_key
and observation.event != "selected"
verdicts = await self.recurrence.verdicts_for_target(
connection,
self.scope_id,
artifact_ref,
cue_key,
)
streak = terminal_streak(verdicts)
if streak < RECURRENCE_REVIEW_STREAK_THRESHOLD:
Expand All @@ -349,7 +362,8 @@ async def _freeze_matches(
*,
row: StoredSource,
outcome: TaskOutcome,
contents: _Contents,
contents: _Contents | None,
load_contents: Callable[[], Awaitable[_Contents]] | None = None,
mode: CandidateSetMode,
) -> tuple[RecurrenceMatch, ...]:
"""Load or derive one matching decision per failure evidence item.
Expand All @@ -359,6 +373,7 @@ async def _freeze_matches(
"""

matches: list[RecurrenceMatch] = []
resolved_contents = contents
for failure_ref in failure_refs(outcome, row.ref):
existing = await self.recurrence.find_match(connection, self.scope_id, row.ref, failure_ref)
if existing is not None:
Expand All @@ -369,14 +384,16 @@ async def _freeze_matches(
continue
if not await self._item_evidence_available(connection, item):
continue
if resolved_contents is None:
resolved_contents = () if load_contents is None else await load_contents()
candidates = freeze_candidate_set(
mode=mode,
refs=tuple(ref for ref, _ in contents),
refs=tuple(ref for ref, _ in resolved_contents),
)
eligible = eligible_candidates(failure_item_text(item), contents)
eligible = eligible_candidates(failure_item_text(item), resolved_contents)
result = match_result(len(eligible))
target = eligible[0] if result == "matched" else None
target_content = None if target is None else _content_of(contents, target)
target_content = None if target is None else _content_of(resolved_contents, target)
match = RecurrenceMatch(
scope_id=self.scope_id,
task_outcome_ref=row.ref,
Expand Down Expand Up @@ -531,13 +548,6 @@ async def _contents(self, connection: AsyncConnection, refs: tuple[ArtifactRef,
contents.append((artifact.as_ref(), artifact.content))
return tuple(contents)

async def _experience_content(self, connection: AsyncConnection, ref: ArtifactRef, /) -> ExperienceContent | None:
try:
artifact = await self.artifacts.get(connection, self.scope_id, ref)
except RepositoryNotFoundError:
return None
return artifact.content if isinstance(artifact.content, ExperienceContent) else None

async def _item_evidence_available(self, connection: AsyncConnection, item: Any, /) -> bool:
sources, artifacts = _citation_refs(getattr(item, "evidence", ()))
try:
Expand Down
9 changes: 9 additions & 0 deletions tests/builtin/persistence/test_experience_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,15 @@ async def scenario() -> None:
current = await contexts.search_experience(scope_id, "falconcurrent", 8)
assert tuple(hit.artifact_ref for hit in current) == (replaced.result_artifact,)

async with contexts.database.transaction() as connection:
await connection.exec_driver_sql(
"INSERT INTO pc_artifact_fts (scope_id, family, artifact_id, revision, searchable_text) "
"SELECT scope_id, family, artifact_id, revision, 'mismatchedprojection falsekeyword' "
"FROM pc_artifact_heads WHERE scope_id = ? AND family = 'experience'",
(scope_id,),
)
assert await contexts.search_experience(scope_id, "mismatchedprojection falsekeyword absent", 8) == ()

skill_candidate = await review.propose_skill(
_skill(),
sources=(context.sources.catalog.as_ref(second_source),),
Expand Down
Loading
Loading