Skip to content
Open
Show file tree
Hide file tree
Changes from 7 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 @@ -506,6 +506,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 @@ -525,6 +528,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.

Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
ATOMIC_MEMORY_PROJECTION_FORMAT,
atomic_memory_current_table,
)
from powercontext.builtin.persistence.oceanbase.schema import create_vector_index
from powercontext.builtin.persistence.schema import create_tables

_FTS_INDEX_NAME = "ix_pc_atomic_memory_current_fts"
Expand Down Expand Up @@ -100,9 +101,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 All @@ -127,12 +131,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
104 changes: 104 additions & 0 deletions src/powercontext/builtin/persistence/oceanbase/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# 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, quoted_name: str, quoted_column: str, parameters: str) -> bool:
match = re.search(
r"^\s*VECTOR\s+(?:KEY|INDEX)\s+" + quoted_name + r"\s*\(\s*" + quoted_column + 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+" + quoted_name + 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]
quoted_name = re.escape(preparer.quote_identifier(name))
quoted_column = re.escape(preparer.quote_identifier(column.name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Recognize unquoted native index definitions

With sql_quote_show_create=OFF, OceanBase returns VECTOR KEY ix_pc_atomic_memory_current_embedding (embedding) ..., so these mandatory quoted patterns never match the existing index. Reinitialization then issues CREATE again and fails with 1235, aborting Atomic Memory initialization. On real OceanBase CE 4.3.5.5, the complete OceanBaseAtomicMemoryIndex(profile).initialize(connection) succeeds at merge base 5032075, fails at c4301849 against the same provisioned database with this session setting, and succeeds again after only restoring sql_quote_show_create=ON. Please support both valid SHOW CREATE forms, or normalize the setting while preserving the caller's session state, so compatible existing indexes remain reusable.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on 8cabe99af6c59f27b2189479bee87b784c87423a against native OceanBase CE 4.4.2.1: the live regression confirms unquoted SHOW CREATE output and successful Atomic Memory reinitialization with sql_quote_show_create=OFF. Concurrent and repeated native-vector initialization also passed. This finding is fixed.


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, quoted_name, quoted_column, 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.tables import (
TOPIC_MEMORY_ACTIVE_CHUNKS_TABLE,
TOPIC_MEMORY_ACTIVE_TOPICS_TABLE,
Expand Down Expand Up @@ -154,13 +155,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 @@ -339,7 +341,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 @@ -422,7 +424,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 @@ -71,6 +71,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
49 changes: 34 additions & 15 deletions src/powercontext/server/authz/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@
from datetime import UTC, datetime
from uuid import uuid4

from sqlalchemy.exc import IntegrityError

from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile
from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile
from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile
from powercontext.builtin.runtime.composition import BuiltinConfigurationError
from powercontext.builtin.runtime.config import DatabaseConfig
from powercontext.server.authz.casbin import CasbinAuthorizationProvider
from powercontext.server.authz.errors import AccessConflictError
from powercontext.server.authz.models import (
DEFAULT_DEPLOYMENT_ID,
AccessBinding,
Expand Down Expand Up @@ -132,22 +135,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")
Loading
Loading