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
4 changes: 4 additions & 0 deletions desktop/src-tauri/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,9 @@ mod tests {
"1.2.0",
"1.3.1",
"1.3.1.dev2+g338dfa00d",
"1.3.1.dev7+gfe12467a5",
"1.4.1",
"1.4.1.dev1+build_1",
"2.0.0",
"2.0.0rc1",
"2.0.0.post1",
Expand All @@ -588,6 +591,7 @@ mod tests {
"not-a-version",
"+1.3.1",
"1.2.1.dev86 with spaces",
"1.4.1;unexpected-command",
"1.2.1.dev86+未知",
] {
assert_eq!(cli_version_from_output(version.as_bytes(), 0), None);
Expand Down
4 changes: 2 additions & 2 deletions release/upgrade-support.json

Large diffs are not rendered by default.

49 changes: 34 additions & 15 deletions src/powercontext/builtin/authz/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
from datetime import UTC, datetime
from uuid import uuid4

from sqlalchemy.exc import IntegrityError

from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider
from powercontext.builtin.authz.errors import AccessConflictError
from powercontext.builtin.authz.models import (
DEFAULT_DEPLOYMENT_ID,
AccessBinding,
Expand Down Expand Up @@ -143,22 +146,38 @@ async def _bootstrap_server_roles(
for principal in principals:
for role in (AccessRole.SERVER_OBSERVER, AccessRole.SERVER_ADMIN):
key = f"static-preset:{deployment_id}:{principal.id}:{role.value}"
await repository.create_binding(
AccessBinding(
binding_id=str(uuid4()),
subject=principal,
resource=resource,
role=role,
granted_by=principal,
reason="static bearer preset",
created_at=datetime.now(UTC),
expires_at=None,
state=AccessBindingState.ACTIVE,
version=1,
policy_revision="pending",
idempotency_key=key,
)
binding = AccessBinding(
binding_id=str(uuid4()),
subject=principal,
resource=resource,
role=role,
granted_by=principal,
reason="static bearer preset",
created_at=datetime.now(UTC),
expires_at=None,
state=AccessBindingState.ACTIVE,
version=1,
policy_revision="pending",
idempotency_key=key,
)
for attempt in range(3):
try:
await repository.create_binding(binding)
break
except AccessConflictError as error:
cause = error.__cause__
# Concurrent MySQL startup can lose the first policy-head
# insert or idempotency-record insert. The failed transaction
# has rolled back; replay the same preset key in a new one.
if (
attempt == 2
or error.code not in {"binding-version", "idempotency-key"}
or not isinstance(cause, IntegrityError)
or cause.orig is None
or not cause.orig.args
or cause.orig.args[0] != 1062
):
raise


__all__ = ("open_builtin_access_control", "open_casbin_access_control")
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
ATOMIC_MEMORY_PROJECTION_FORMAT,
atomic_memory_current_table,
)
from powercontext.builtin.persistence.oceanbase.schema import create_vector_index
from powercontext.builtin.persistence.oceanbase.vector import OceanBaseVector
from powercontext.builtin.persistence.schema import create_tables

Expand Down Expand Up @@ -171,9 +172,12 @@ async def initialize(self, connection: AsyncConnection, /) -> None:
await create_tables(connection, self.tables)
await self.require_current_schema(connection)
try:
# Existing deployments may use a DML-only runtime account. Even
# IF NOT EXISTS requires CREATE privileges on OceanBase.
if not await connection.scalar(_INDEX_EXISTS, {"index_name": _FTS_INDEX_NAME}):
await connection.exec_driver_sql(
f"CREATE FULLTEXT INDEX {_FTS_INDEX_NAME} ON pc_atomic_memory_current (searchable_text) WITH PARSER SPACE"
f"CREATE FULLTEXT INDEX IF NOT EXISTS {_FTS_INDEX_NAME} "
"ON pc_atomic_memory_current (searchable_text) WITH PARSER SPACE"
)
await connection.exec_driver_sql(
"SELECT artifact_id FROM pc_atomic_memory_current "
Expand Down Expand Up @@ -241,12 +245,10 @@ async def _initialize_vectors(self, connection: AsyncConnection) -> None:
f"Atomic Memory uses {column_type!r}; expected {expected}. "
"Reconfigure the current vector column offline and rebuild vectors before vector search.",
)
if self._vector_index is not None and not await connection.scalar(
_INDEX_EXISTS, {"index_name": _VECTOR_INDEX_NAME}
):
if self._vector_index is not None:
vector_index = self._vector_index
try:
await connection.run_sync(lambda sync: vector_index.create(sync, checkfirst=False))
await create_vector_index(connection, vector_index)
except SQLAlchemyError as error:
raise AtomicMemoryIndexError(
"oceanbase-vector", "OceanBase native Atomic Memory vector index is unavailable"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@

_OCEANBASE_FTS_INDEX_NAME = "ix_pc_artifact_heads_fts"
_OCEANBASE_CREATE_FTS_SQL = f"""
CREATE FULLTEXT INDEX {_OCEANBASE_FTS_INDEX_NAME}
CREATE FULLTEXT INDEX IF NOT EXISTS {_OCEANBASE_FTS_INDEX_NAME}
ON pc_artifact_heads (searchable_text) WITH PARSER SPACE
"""

_OCEANBASE_FTS_INDEX_EXISTS_SQL = text(
"""
SELECT COUNT(*)
Expand All @@ -68,10 +69,9 @@ async def initialize(self, connection: AsyncConnection, /) -> None:
if connection.dialect.name != "mysql":
raise CapabilityNotSupportedError("oceanbase-experience-fts")
await ensure_artifact_head_searchable_text(connection)
count = await connection.scalar(
_OCEANBASE_FTS_INDEX_EXISTS_SQL,
{"index_name": _OCEANBASE_FTS_INDEX_NAME},
)
# Keep provisioned schemas usable without runtime CREATE privileges;
# native IF NOT EXISTS still closes a concurrent missing-index race.
count = await connection.scalar(_OCEANBASE_FTS_INDEX_EXISTS_SQL, {"index_name": _OCEANBASE_FTS_INDEX_NAME})
if count == 0:
await connection.exec_driver_sql(_OCEANBASE_CREATE_FTS_SQL)
if not await lexical_projection_is_current(
Expand Down
105 changes: 105 additions & 0 deletions src/powercontext/builtin/persistence/oceanbase/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Copyright (c) 2026 OceanBase.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Native idempotent OceanBase vector-index DDL."""

import asyncio
import re
import time

from pyobvector import VectorIndex
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncConnection


def _parameters(value: str) -> dict[str, str]:
return {
key.strip().lower(): setting.strip().lower()
for part in value.split(",")
if "=" in part
for key, setting in [part.split("=", 1)]
}


def _matching_definition(definition: str, name_pattern: str, column_pattern: str, parameters: str) -> bool:
match = re.search(
r"^\s*VECTOR\s+(?:KEY|INDEX)\s+" + name_pattern + r"\s*\(\s*" + column_pattern + r"\s*\)\s+WITH\s*\(([^)]*)\)",
definition,
re.IGNORECASE | re.MULTILINE,
)
if match and all(_parameters(match[1]).get(key) == value for key, value in _parameters(parameters).items()):
return True
if re.search(
r"^\s*(?:(?:UNIQUE|FULLTEXT|VECTOR|SPATIAL)\s+)?(?:KEY|INDEX)\s+" + name_pattern + r"\s*\(",
definition,
re.IGNORECASE | re.MULTILINE,
):
message = "An existing OceanBase vector index does not match its native column or parameters"
raise SQLAlchemyError(message)
return False


async def create_vector_index(connection: AsyncConnection, index: VectorIndex, /) -> None:
table, name = index.table, index.name
if table is None or name is None:
message = "A native vector index must have a name and bound table"
raise ValueError(message)
preparer = connection.dialect.identifier_preparer
columns = tuple(index.columns)
column = columns[0]
# SHOW CREATE TABLE omits identifier quotes with sql_quote_show_create=OFF.
name_pattern = "(?:" + re.escape(preparer.quote_identifier(name)) + "|" + re.escape(name) + ")"
column_pattern = "(?:" + re.escape(preparer.quote_identifier(column.name)) + "|" + re.escape(column.name) + ")"

async def existing_matches() -> bool:
result = await connection.exec_driver_sql(f"SHOW CREATE TABLE {preparer.format_table(table)}")
row = result.first()
definition = "" if row is None else str(row[1])
# STATISTICS exposes hidden BTREE auxiliary columns for VECTOR indexes.
return _matching_definition(definition, name_pattern, column_pattern, index.params or "")

# 4.4.2.1 rejects another VECTOR index on the column before honoring
# IF NOT EXISTS. Revalidate only that exact duplicate-column race.
if await existing_matches():
return
parameters = "" if index.params is None else f" WITH ({index.params})"
names = ", ".join(preparer.format_column(value) for value in columns)
try:
await connection.exec_driver_sql(
f"CREATE VECTOR INDEX IF NOT EXISTS {preparer.format_index(index)} "
f"ON {preparer.format_table(table)} ({names}){parameters}"
)
except DBAPIError as error:
original = error.orig
if (
original is None
or not original.args
or original.args[0] != 1235
or not str(original.args[1] if len(original.args) > 1 else "")
.lower()
.startswith("create vector index on column has vector index is not supported")
):
raise
# The native column reservation becomes visible before its logical
# index DDL. Wait for the competing creation's metadata to settle,
# using the tenant's existing query timeout; never replay CREATE.
result = await connection.exec_driver_sql("SELECT @@ob_query_timeout")
deadline = time.monotonic() + max(0, int(result.scalar_one())) / 1_000_000
while True:
if await existing_matches():
return
remaining = deadline - time.monotonic()
if remaining <= 0:
raise
await asyncio.sleep(min(0.1, remaining))
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
TopicMemorySearchRequest,
TopicMemoryStorageInvariantError,
)
from powercontext.builtin.persistence.oceanbase.schema import create_vector_index
from powercontext.builtin.persistence.oceanbase.vector import OceanBaseVector
from powercontext.builtin.persistence.tables import (
TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE,
Expand Down Expand Up @@ -155,13 +156,14 @@ async def validate_current(self, _connection: AsyncConnection, /) -> None:
async def initialize(self, connection: AsyncConnection, /) -> None:
if connection.dialect.name != "mysql":
raise TopicMemoryCapabilityError("oceanbase-fts")
await self._ensure_index(connection, TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.name, _TOPIC_FTS_INDEX)
await self._ensure_index(connection, TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE.name, _CHUNK_FTS_INDEX)
await connection.execute(
select(TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.artifact_id)
.where(match(TOPIC_MEMORY_ACTIVE_TOPICS_TABLE.c.searchable_text, against="powercontext"))
.limit(1)
)
for table, index_name in (
(TOPIC_MEMORY_ACTIVE_TOPICS_TABLE, _TOPIC_FTS_INDEX),
(TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE, _CHUNK_FTS_INDEX),
):
await self._ensure_index(connection, table.name, index_name)
await connection.execute(
select(table.c.artifact_id).where(match(table.c.searchable_text, against="powercontext")).limit(1)
)

async def replace(
self,
Expand Down Expand Up @@ -340,7 +342,7 @@ async def _ensure_index(connection: AsyncConnection, table_name: str, index_name
return
try:
await connection.exec_driver_sql(
f"CREATE FULLTEXT INDEX {index_name} ON {table_name} (searchable_text) WITH PARSER SPACE"
f"CREATE FULLTEXT INDEX IF NOT EXISTS {index_name} ON {table_name} (searchable_text) WITH PARSER SPACE"
)
except OperationalError as error:
# OceanBase maps a NOWAIT DDL lock conflict to MySQL 1205.
Expand Down Expand Up @@ -423,7 +425,7 @@ async def initialize(self, connection: AsyncConnection, /) -> None:
)
for attempt in range(len(_INDEX_DDL_RETRY_DELAYS) + 1):
try:
await connection.run_sync(lambda sync: self._topic_index.create(sync, checkfirst=True))
await create_vector_index(connection, self._topic_index)
except OperationalError as error:
if (
error.orig is None
Expand Down
3 changes: 3 additions & 0 deletions src/powercontext/builtin/persistence/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ def _create_mysql_tables(connection: Connection, tables: Sequence[Table]) -> Non
continue
connection.execute(CreateTable(table, if_not_exists=True))
for index in sorted(table.indexes, key=lambda item: str(item.name)):
# Specialized VECTOR DDL belongs to its native initializer.
if index.__visit_name__ != "index":
continue
try:
index.create(connection, checkfirst=True)
except DBAPIError as error:
Expand Down
21 changes: 21 additions & 0 deletions tests/builtin/persistence/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,34 @@

import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock

import pytest

from powercontext.builtin.persistence import schema
from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile
from powercontext.builtin.persistence.tables import BUILTIN_TABLES


@pytest.fixture
def mock_installed_evidence_schema(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep native index tests independent of the separately tested evidence migration."""
monkeypatch.setattr(schema, "apply_atomic_memory_evidence_migration", AsyncMock())


@pytest.fixture
def mock_provisioned_mysql_connection(
monkeypatch: pytest.MonkeyPatch, mock_installed_evidence_schema: None
) -> MagicMock:
"""Run synchronous index probes with existing tables and a stable engine pool."""
connection = MagicMock()
inspector = MagicMock()
inspector.get_table_names.return_value = []
inspector.has_table.return_value = True
monkeypatch.setattr(schema, "inspect", lambda _connection: inspector)
return connection


@pytest.fixture
def initialized_sqlite_database(tmp_path: Path) -> Path:
"""Keep unrelated schemas ready while a test restores its target's legacy shape."""
Expand Down
Loading
Loading