Skip to content
Open
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
29 changes: 25 additions & 4 deletions src/powercontext/builtin/review/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,8 +656,22 @@ async def reject(
)
return _reviewed_candidate(rejected)

async def approve(self, candidate_id: str, expected_version: int, /) -> ReviewedCandidate:
"""Publish once and return the stored result for overlapping approval retries."""
async def approve(
self,
candidate_id: str,
expected_version: int,
/,
*,
on_commit: CandidateCommitHook | None = None,
) -> ReviewedCandidate:
"""Publish once and return the stored result for overlapping approval retries.

For Experience, Skill (including Dream ``derive_skill``), and Profile
Candidates, ``on_commit`` runs inside the transaction that publishes the
result, so writes it makes commit or roll back with the approval. It
never runs for the target-revising Dream families (Atomic Memory, Topic
Memory, Handoff, and Prompt) or when the Candidate was already approved.
"""

async with self._connection() as connection:
current = await self._candidates.get(connection, self._scope_id, candidate_id)
Expand All @@ -670,7 +684,7 @@ async def approve(self, candidate_id: str, expected_version: int, /) -> Reviewed
else nullcontext()
):
try:
return await self._approve(current, expected_version)
return await self._approve(current, expected_version, on_commit=on_commit)
except (ArtifactTargetConflictError, CandidateTerminalError, RevisionConflictError):
# Another instance can publish after our pending read. Leave the failed
# transaction before reading the terminal decision; never
Expand All @@ -689,6 +703,8 @@ async def _approve( # noqa: C901 - each Family keeps its own transactional publ
current: Candidate[Any],
expected_version: int,
/,
*,
on_commit: CandidateCommitHook | None,
) -> ReviewedCandidate:
"""Atomically commit the reviewed Artifact and Candidate result."""

Expand All @@ -713,7 +729,10 @@ async def _approve( # noqa: C901 - each Family keeps its own transactional publ
if current.status is CandidateStatus.REJECTED:
raise CandidateTerminalError(candidate_id, current.status)
if current.family == "profile":
return _reviewed_candidate(await decide_profile(self, connection, candidate_id, expected_version))
approved = await decide_profile(self, connection, candidate_id, expected_version)
if on_commit is not None:
await on_commit(connection, approved)
return _reviewed_candidate(approved)
if current.version != expected_version:
raise CandidateConflictError(candidate_id, expected_version, current.version)
_validate_approval_lineage(_reviewed_candidate(current))
Expand Down Expand Up @@ -788,6 +807,8 @@ async def _approve( # noqa: C901 - each Family keeps its own transactional publ
expected_version,
artifact.as_ref(),
)
if on_commit is not None:
await on_commit(connection, approved)
return _reviewed_candidate(approved)

async def require_prompt_target(self, target: ArtifactRef, /) -> dict[str, object]:
Expand Down
13 changes: 12 additions & 1 deletion src/powercontext/builtin/runtime/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -3980,7 +3980,17 @@ async def inspect_evidence(self, candidate_id: str, expected_version: int):
return await self._runtime._catalog_review(self.scope_id).evidence(candidate_id)
return await self._runtime._review(self.scope_id).inspect_evidence(candidate_id, expected_version)

async def approve(self, request: ApproveCandidateRequest, /) -> ReviewedCandidate:
async def approve(
self,
request: ApproveCandidateRequest,
/,
*,
on_commit: CandidateCommitHook | None = None,
) -> ReviewedCandidate:
"""Approve a Candidate; ``on_commit`` follows ``ReviewService.approve``.

Tag Candidates publish no result Artifact and never run ``on_commit``.
"""
async with self._runtime._scoped_operation(self.scope_id), self._runtime._locked(self.scope_id):
current = await self.get(GetCandidateRequest(candidate_id=request.candidate_id))
if current.candidate_kind == "tag":
Expand All @@ -3994,6 +4004,7 @@ async def approve(self, request: ApproveCandidateRequest, /) -> ReviewedCandidat
return await self._runtime._review(self.scope_id).approve(
request.candidate_id,
request.expected_version,
on_commit=on_commit,
)

async def reject(self, request: RejectCandidateRequest, /) -> ReviewedCandidate:
Expand Down
73 changes: 52 additions & 21 deletions src/powercontext/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@
AuditSearchRequest,
AuthorizedResourceFilter,
BindingSearchRequest,
CandidateOwnerAttestation,
CreateBinding,
GroupRef,
MemoryEntrySelector,
Expand Down Expand Up @@ -6145,8 +6146,13 @@ async def approve_candidate(
attestation = None if access is None else await access.candidate_owner(request.scope_id, request.candidate_id)
if access is not None and attestation is None:
raise AccessUnavailableError("artifact_owner_pending")
owner_key = bounded_idempotency_key("candidate-artifact-owner", request.scope_id, request.candidate_id)
context = _access_audit_context(APPROVE_CANDIDATE.operation_id)
try:
result = await review.approve(mapping.approve_candidate_request(request))
result = await review.approve(
mapping.approve_candidate_request(request),
**_approval_owner_commit(http_request, attestation, idempotency_key=owner_key, context=context),
)
except CandidateTerminalError:
current = await review.get(RuntimeGetCandidateRequest(candidate_id=request.candidate_id))
if current.status.value != "approved" or current.version != request.expected_version:
Expand All @@ -6156,29 +6162,54 @@ async def approve_candidate(
artifact = result.result_artifact
if artifact is None:
raise AccessUnavailableError("artifact_owner_pending")
try:
await access.establish_artifact_owner(
ResourceRef.artifact(
request.scope_id,
family=artifact.family,
artifact_id=artifact.artifact_id,
),
attestation.proposed_owner,
idempotency_key=bounded_idempotency_key(
"candidate-artifact-owner", request.scope_id, request.candidate_id
),
context=_access_audit_context(APPROVE_CANDIDATE.operation_id),
)
except AccessConflictError:
# Ownership migration may already have recorded this owner under its own idempotency key.
existing = await access.artifact_owner(
ResourceRef.artifact(request.scope_id, family=artifact.family, artifact_id=artifact.artifact_id)
)
if existing is None or existing.owner != attestation.proposed_owner:
raise
resource = ResourceRef.artifact(request.scope_id, family=artifact.family, artifact_id=artifact.artifact_id)
# Deliver the owner staged with this approval, including one staged by an earlier attempt.
await flush_owner_writes(artifact=resource)
existing = await access.artifact_owner(resource)
if existing is None or existing.owner != attestation.proposed_owner:
# The approval committed without its owner: owner writes could not join its transaction.
try:
await access.establish_artifact_owner(
resource,
attestation.proposed_owner,
idempotency_key=owner_key,
context=context,
)
except AccessConflictError:
# Ownership migration may already have recorded this owner under its own idempotency key.
existing = await access.artifact_owner(resource)
if existing is None or existing.owner != attestation.proposed_owner:
raise
return await _candidate_response(http_request, request.scope_id, result)


def _approval_owner_commit(
request: Request,
attestation: CandidateOwnerAttestation | None,
*,
idempotency_key: str,
context: AccessAuditContext,
) -> dict[str, Any]:
"""Commit a new result Artifact's owner or recovery intent with the approval so migration cannot claim it."""
access = _transactional_owner_access(request)
if access is None or attestation is None or attestation.target is not None:
return {}
scope_id, owner = attestation.scope_id, attestation.proposed_owner

async def on_commit(connection, candidate):
artifact = candidate.result_artifact
if artifact is None:
raise AccessUnavailableError("artifact_owner_pending")
await owner_write_access(access, connection).establish_artifact_owner(
ResourceRef.artifact(scope_id, family=artifact.family, artifact_id=artifact.artifact_id),
owner,
idempotency_key=idempotency_key,
context=context,
)

return {"on_commit": on_commit}


async def reject_candidate(
request: RejectCandidateRequest,
application: Annotated[ServerApplication, Depends(_require_application)],
Expand Down
Loading
Loading