mchades commented on code in PR #12859:
URL: https://github.com/apache/gravitino/pull/12859#discussion_r4130718064


##########
clients/client-python/gravitino/dto/semantic/semantic_model_definition_dto.py:
##########
@@ -0,0 +1,121 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+from dataclasses import dataclass, field
+from typing import Optional
+
+from dataclasses_json import DataClassJsonMixin, config
+
+from gravitino.api.semantic.semantic_model_definition import 
SemanticModelDefinition
+from gravitino.dto.semantic.ai_context_dto import AIContextDTO
+from gravitino.dto.semantic.custom_extension_dto import CustomExtensionDTO
+from gravitino.dto.semantic.dataset_dto import DatasetDTO
+from gravitino.dto.semantic.json_serdes.ai_context_serdes import 
AIContextSerdes
+from gravitino.dto.semantic.metric_dto import MetricDTO
+from gravitino.dto.semantic.relationship_dto import RelationshipDTO
+from gravitino.dto.semantic.semantic_dto_utils import convert_list, is_none
+
+
+@dataclass
+class SemanticModelDefinitionDTO(DataClassJsonMixin):
+    """Represents a Semantic Model definition DTO."""
+
+    _ai_context: Optional[AIContextDTO] = field(
+        default=None,
+        metadata=config(
+            field_name="ai_context",

Review Comment:
   [P1] Match the current Java DTO wire names
   
   The Java DTOs on this PR's base use `aiContext`, `customExtensions`, 
`primaryKey`, `uniqueKeys`, `isTime`, `vendorName`, `fromColumns` and 
`toColumns`. These Python DTOs use snake_case instead. Deserializing Java JSON 
silently drops the optional fields; a definition containing a relationship 
fails in `to_definition()` with `fromColumns must not be null or empty`. Please 
align all field mappings with the Java DTOs and test against their JSON 
fixtures; Python-only round trips currently hide this incompatibility.



##########
clients/client-python/gravitino/dto/semantic/json_serdes/ai_context_serdes.py:
##########
@@ -0,0 +1,104 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+from typing import Any, Optional, Union
+
+from gravitino.dto.semantic.ai_context_dto import AIContextDTO
+from gravitino.dto.semantic.ai_context_object_dto import AIContextObjectDTO
+from gravitino.utils.precondition import Precondition
+
+_INSTRUCTIONS = "instructions"
+_SYNONYMS = "synonyms"
+_EXAMPLES = "examples"
+
+
+class AIContextSerdes:
+    """Serdes for AI context DTOs.
+
+    An AI context is either a bare JSON string or a JSON object whose unknown
+    properties are retained losslessly.
+    """
+
+    @staticmethod
+    def serialize(
+        value: Optional[AIContextDTO],
+    ) -> Optional[Union[str, dict[str, Any]]]:
+        """Encode an AI context DTO to a string or a dictionary."""
+        if value is None:
+            return None
+        if value.text() is not None:
+            return value.text()
+        return _serialize_object(value.object())
+
+    @staticmethod
+    def deserialize(
+        value: Optional[Union[str, dict[str, Any]]],
+    ) -> Optional[AIContextDTO]:
+        """Decode an AI context DTO from a string or a dictionary."""
+        if value is None:
+            return None
+        if isinstance(value, str):
+            return AIContextDTO(text=value)
+        Precondition.check_argument(
+            isinstance(value, dict), "AI context must be a string or object"
+        )
+        return AIContextDTO(obj=_deserialize_object(value))
+
+
+def _serialize_object(value: AIContextObjectDTO) -> dict[str, Any]:
+    serialized: dict[str, Any] = {}
+    if value.instructions() is not None:
+        serialized[_INSTRUCTIONS] = value.instructions()
+    if value.synonyms() is not None:
+        serialized[_SYNONYMS] = value.synonyms()
+    if value.examples() is not None:
+        serialized[_EXAMPLES] = value.examples()
+    serialized.update(value.additional_properties())

Review Comment:
   [P2] Preserve decimal numbers across JSON serialization
   
   The API accepts lossless `Decimal` values, but passing them through here 
lets `dataclasses-json` encode them as strings: 
`Decimal("0.123456789012345678901234567890")` becomes a quoted JSON value, and 
the restored API object contains a string. In the other direction, default 
`from_json()` rounds the corresponding JSON number to `0.12345678901234568`. 
Please preserve numeric type and precision in both directions, including nested 
additional properties, as the Java serde does.



##########
clients/client-python/gravitino/dto/semantic/ai_context_object_dto.py:
##########
@@ -0,0 +1,109 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+import copy
+from typing import Any, Optional
+
+from gravitino.api.semantic.ai_context_object import AIContextObject
+
+
+class AIContextObjectDTO:
+    """Represents a structured AI context DTO.
+
+    Unknown properties are carried in `additional_properties` and are flattened
+    next to the standard properties on the wire.
+    """
+
+    def __init__(
+        self,
+        instructions: Optional[str] = None,
+        synonyms: Optional[list[str]] = None,
+        examples: Optional[list[str]] = None,
+        additional_properties: Optional[dict[str, Any]] = None,
+    ):
+        self._instructions = instructions
+        self._synonyms = None if synonyms is None else list(synonyms)
+        self._examples = None if examples is None else list(examples)
+        self._additional_properties = (
+            {}
+            if additional_properties is None
+            else copy.deepcopy(additional_properties)
+        )
+
+    def instructions(self) -> Optional[str]:
+        """Returns the free-form instructions, or `None` if it is not set."""
+        return self._instructions
+
+    def synonyms(self) -> Optional[list[str]]:
+        """Returns the synonyms, or `None` if they are not set."""
+        return None if self._synonyms is None else list(self._synonyms)
+
+    def examples(self) -> Optional[list[str]]:
+        """Returns the examples, or `None` if they are not set."""
+        return None if self._examples is None else list(self._examples)
+
+    def additional_properties(self) -> dict[str, Any]:
+        """Returns the additional properties, empty if none are set."""
+        return copy.deepcopy(self._additional_properties)
+
+    @staticmethod
+    def from_ai_context_object(
+        ai_context_object: AIContextObject,
+    ) -> "AIContextObjectDTO":
+        """Convert a structured AI context to its DTO."""
+        return AIContextObjectDTO(
+            instructions=ai_context_object.instructions(),
+            synonyms=ai_context_object.synonyms(),
+            examples=ai_context_object.examples(),
+            additional_properties=ai_context_object.additional_properties(),
+        )
+
+    def to_ai_context_object(self) -> AIContextObject:
+        """Convert this DTO to a structured AI context."""
+        return AIContextObject(
+            instructions=self._instructions,
+            synonyms=self._synonyms,
+            examples=self._examples,
+            additional_properties=self._additional_properties,
+        )
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, AIContextObjectDTO):
+            return False
+        return (
+            self._instructions == other.instructions()
+            and self._synonyms == other.synonyms()
+            and self._examples == other.examples()
+            and self._additional_properties == other.additional_properties()

Review Comment:
   [P2] Keep additional-property equality consistent with the API
   
   Plain dict equality makes contexts containing `{"flag": True}` and `{"flag": 
1}` equal here, although the API objects and JSON values differ. It also makes 
`0.1` and `Decimal("0.1")` unequal, although the API treats them as equal. This 
propagates into definition/model DTO equality. Please reuse the API's 
recursive, type-aware comparison and cover nested values.



##########
clients/client-python/gravitino/dto/semantic/json_serdes/ai_context_serdes.py:
##########
@@ -0,0 +1,104 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+from typing import Any, Optional, Union
+
+from gravitino.dto.semantic.ai_context_dto import AIContextDTO
+from gravitino.dto.semantic.ai_context_object_dto import AIContextObjectDTO
+from gravitino.utils.precondition import Precondition
+
+_INSTRUCTIONS = "instructions"
+_SYNONYMS = "synonyms"
+_EXAMPLES = "examples"
+
+
+class AIContextSerdes:
+    """Serdes for AI context DTOs.
+
+    An AI context is either a bare JSON string or a JSON object whose unknown
+    properties are retained losslessly.
+    """
+
+    @staticmethod
+    def serialize(
+        value: Optional[AIContextDTO],
+    ) -> Optional[Union[str, dict[str, Any]]]:
+        """Encode an AI context DTO to a string or a dictionary."""
+        if value is None:
+            return None
+        if value.text() is not None:
+            return value.text()
+        return _serialize_object(value.object())
+
+    @staticmethod
+    def deserialize(
+        value: Optional[Union[str, dict[str, Any]]],
+    ) -> Optional[AIContextDTO]:
+        """Decode an AI context DTO from a string or a dictionary."""
+        if value is None:
+            return None
+        if isinstance(value, str):
+            return AIContextDTO(text=value)
+        Precondition.check_argument(
+            isinstance(value, dict), "AI context must be a string or object"
+        )
+        return AIContextDTO(obj=_deserialize_object(value))
+
+
+def _serialize_object(value: AIContextObjectDTO) -> dict[str, Any]:
+    serialized: dict[str, Any] = {}
+    if value.instructions() is not None:
+        serialized[_INSTRUCTIONS] = value.instructions()
+    if value.synonyms() is not None:
+        serialized[_SYNONYMS] = value.synonyms()
+    if value.examples() is not None:
+        serialized[_EXAMPLES] = value.examples()
+    serialized.update(value.additional_properties())
+    return serialized
+
+
+def _deserialize_object(value: dict[str, Any]) -> AIContextObjectDTO:
+    additional_properties = {
+        name: item
+        for name, item in value.items()
+        if name not in (_INSTRUCTIONS, _SYNONYMS, _EXAMPLES)
+    }
+    return AIContextObjectDTO(
+        instructions=_read_string(value, _INSTRUCTIONS),
+        synonyms=_read_string_list(value, _SYNONYMS),
+        examples=_read_string_list(value, _EXAMPLES),
+        additional_properties=additional_properties,
+    )
+
+
+def _read_string(value: dict[str, Any], name: str) -> Optional[str]:
+    if name not in value:
+        return None
+    item = value[name]
+    Precondition.check_argument(isinstance(item, str), f"{name} must be a 
string")

Review Comment:
   [P2] Accept explicit null for optional AI-context properties
   
   `AIContextSerdes.deserialize({"instructions": None})` raises here, and 
`synonyms: null` / `examples: null` fail in `_read_string_list` too. Java 
explicitly accepts these values as unset in 
`testAIContextObjectExplicitNullHandling`. Please return `None` for explicit 
null as well as missing keys in both helpers, while still rejecting null 
elements inside the string arrays.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to