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
5 changes: 5 additions & 0 deletions packages/dsw-document-worker/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Changed

- Document context metamodel 19.1; contexts of 19.0 are still rendered, newer minor versions are
rejected


## [5.1.0]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,8 @@ def check_compliance(self):
raise JobError(
job_id=self.doc_uuid,
msg=(f'Unsupported document context metamodel version {shown}, expected '
f'{DOCUMENT_TEMPLATE_METAMODEL_VERSION.major}.x. Regenerate the document.'),
f'{DOCUMENT_TEMPLATE_METAMODEL_VERSION.major}.0 to '
f'{DOCUMENT_TEMPLATE_METAMODEL_VERSION}. Regenerate the document.'),
skip_reporting=True,
) from e

Expand Down
5 changes: 3 additions & 2 deletions packages/dsw-document-worker/tests/test_check_compliance.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ def make_job(doc_context: dict, project_uuid: str | None = None, db=None) -> Job
return job


@pytest.mark.parametrize('version', ['19.0', '19', '19.4'])
@pytest.mark.parametrize('version', ['19.0', '19', '19.1'])
def test_current_metamodel_is_accepted(version):
make_job({'metamodelVersion': version}).check_compliance()


@pytest.mark.parametrize(('version', 'shown'), [
('18.3', '18.3'),
('17', '17.0'),
('19.2', '19.2'),
('20.0', '20.0'),
(None, 'missing'),
('x.y', 'missing'),
Expand All @@ -38,7 +39,7 @@ def test_other_metamodel_asks_for_regeneration(version, shown):
make_job(context).check_compliance()
# exactly what ends up in the document's worker_log
assert error.value.db_message() == (
f'Unsupported document context metamodel version {shown}, expected 19.x. '
f'Unsupported document context metamodel version {shown}, expected 19.0 to 19.1. '
'Regenerate the document.')
assert error.value.skip_reporting # an expected condition, not a bug to report

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
from dsw.models.document_context.graph import check_metamodel_version


@pytest.mark.parametrize('version', ['19.0', '19', '19.9', '19.10'])
@pytest.mark.parametrize('version', ['19.0', '19', '19.1'])
def test_accepted(version):
check_metamodel_version(version)


@pytest.mark.parametrize(('version', 'message'), [
('19.2', 'expected at most 1 minor version'),
('19.10', 'expected at most 1 minor version'),
('18.3', 'expected major version 19'),
('17.9', 'expected major version 19'),
('20.0', 'expected major version 19'),
Expand Down
17 changes: 17 additions & 0 deletions packages/dsw-models/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Knowledge model metamodel 21: optional `prefill` of questions (`QuestionPrefill`) in the flat
model, tree, events, compiler, squash and diff, `prefill_source` in the graph, and the
migration from 20
- Provenance of project events and replies (`PrefillProvenance`)
- `DeleteItemEvent` in project events, changes and compiled project content
- `Question.prefill` and `Reply.provenance` in the document context object model

### Changed

- `KM_METAMODEL_VERSION` is `21`: bundles of version 20 have to be upgraded with `migrate_bundle`
before they are loaded
- `DOCUMENT_TEMPLATE_METAMODEL_VERSION` is `19.1`
- `check_metamodel_version` accepts every minor version up to the current one, so contexts made
before an upgrade still render, and rejects newer ones


## [5.1.0]

Expand Down
3 changes: 2 additions & 1 deletion packages/dsw-models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ keys unless asked otherwise:
```python
import json

from dsw.models.knowledge_model.migrations import migrate_bundle
from dsw.models.knowledge_model.package import KnowledgeModelBundle
from dsw.models.strictness import UnknownKeys, load

with open('dsw_root_2.8.1.km') as file:
bundle = load(KnowledgeModelBundle, json.load(file)) # strict
bundle = load(KnowledgeModelBundle, migrate_bundle(json.load(file))) # strict
# load(KnowledgeModelBundle, data, unknown_keys=UnknownKeys.IGNORE) drops unknown keys

data = bundle.to_json_data() # JSON-compatible data as the server writes it
Expand Down
52 changes: 47 additions & 5 deletions packages/dsw-models/dsw/models/document_context/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


def check_metamodel_version(metamodel_version: str):
"""Accept the same major version and at least the current minor version."""
"""Accept the same major version up to the current minor version."""
current = DOCUMENT_TEMPLATE_METAMODEL_VERSION
try:
version = MetamodelVersion.parse(metamodel_version)
Expand All @@ -33,9 +33,9 @@ def check_metamodel_version(metamodel_version: str):
if version.major != current.major:
raise ValueError(f'Unsupported metamodel version: {metamodel_version} '
f'(expected major version {current.major})')
if version.minor < current.minor:
if version.minor > current.minor:
raise ValueError(f'Unsupported metamodel version: {metamodel_version} '
f'(expected at least {current.minor} minor version)')
f'(expected at most {current.minor} minor version)')


def render_markdown(md_text: str, sanitize: bool = True):
Expand Down Expand Up @@ -609,6 +609,24 @@ def load(data: dict, **options):
)


class ReplyProvenance:

def __init__(self, *, provenance_type: str, source_path: str, integration_uuid: str):
self.type = provenance_type
self.source_path = source_path
self.integration_uuid = integration_uuid

@staticmethod
def load(data: dict | None, **options):
if data is None:
return None
return ReplyProvenance(
provenance_type=data['type'],
source_path=data['sourcePath'],
integration_uuid=data['integrationUuid'],
)


class Reply(abc.ABC):

def __init__(self, *, path: str, created_at: datetime,
Expand All @@ -617,6 +635,7 @@ def __init__(self, *, path: str, created_at: datetime,
self.created_at = created_at
self.created_by = created_by
self.type = reply_type
self.provenance: ReplyProvenance | None = None

self.question: Question | None = None
self.fragments: list[str] = path.split('.')
Expand Down Expand Up @@ -1023,6 +1042,24 @@ def load(data: dict, **options):
)


class QuestionPrefill:

def __init__(self, *, source_question_uuid: str, template: str, integration_only: bool):
self.source_question_uuid = source_question_uuid
self.template = template
self.integration_only = integration_only

@staticmethod
def load(data: dict | None, **options):
if data is None:
return None
return QuestionPrefill(
source_question_uuid=data['sourceQuestionUuid'],
template=data['template'],
integration_only=data['integrationOnly'],
)


class Question(abc.ABC):

def __init__(self, *, uuid: str, q_type: str, title: str, text: str | None,
Expand All @@ -1038,6 +1075,7 @@ def __init__(self, *, uuid: str, q_type: str, title: str, text: str | None,
self.expert_uuids = expert_uuids
self.required_phase_uuid = required_phase_uuid
self.annotations = annotations
self.prefill: QuestionPrefill | None = None

self.is_required: bool | None = None
self.parent: Chapter | ListQuestion | Answer | None = None
Expand Down Expand Up @@ -1562,7 +1600,9 @@ def _load_question(data: dict, **options):
question_class = _QUESTION_TYPES.get(question_type)
if question_class is None:
raise ValueError(f'Unknown question type: {question_type}')
return question_class.load(data, **options)
question = question_class.load(data, **options)
question.prefill = QuestionPrefill.load(data.get('prefill'), **options) # missing in 19.0
return question


def _load_reference(data: dict, **options):
Expand All @@ -1586,7 +1626,9 @@ def _load_reply(path: str, data: dict, **options):
reply_class = _REPLY_TYPES.get(reply_type)
if reply_class is None:
raise ValueError(f'Unknown reply type: {reply_type}')
return reply_class.load(path, data, **options)
reply = reply_class.load(path, data, **options)
reply.provenance = ReplyProvenance.load(data.get('provenance'), **options) # missing in 19.0
return reply


class KnowledgeModelEntities:
Expand Down
2 changes: 1 addition & 1 deletion packages/dsw-models/dsw/models/document_context/wire.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Document context (metamodel 19.0) as the backend sends it.
"""Document context (metamodel 19.1) as the backend sends it.

The same shape is the body of the ``generateDocument`` persistent command (with ``document``) and
the response of the document context endpoints (``document`` is ``null``). Exactly one of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
17.0 ``metamodelVersion`` became a ``"major.minor"`` string
18.3 ``language`` added (default ``"en"``)
19.0 no descriptor change (single ``id``, see below); the document context was restructured
19.1 no descriptor change; questions have ``prefill`` and replies ``provenance`` in the context
======== =============================================================================

Whatever the version, the identity is upgraded to the single ``id`` of Wizard 5.0, as the
Expand Down
10 changes: 10 additions & 0 deletions packages/dsw-models/dsw/models/knowledge_model/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ class MetricMeasure(BaseModel):
weight: float


class QuestionPrefill(BaseModel):
"""The question is prefilled from the item picked in the source question."""

source_question_uuid: UUID
#: Jinja template, its only variable is ``item``
template: str
#: read-only in the questionnaire, always follows its source
integration_only: bool


QuestionValueType = typing.Literal[
'StringQuestionValueType',
'NumberQuestionValueType',
Expand Down
2 changes: 2 additions & 0 deletions packages/dsw-models/dsw/models/knowledge_model/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,8 @@ def convert_entity(entity: typing.Any, target_type: type) -> typing.Any:
"""Change the type of a question, reference or integration like the backend does."""
if issubclass(target_type, flat.QuestionBase):
data = {name: getattr(entity, name) for name in _QUESTION_SHARED_FIELDS}
if target_type not in (flat.ItemSelectQuestion, flat.FileQuestion):
data['prefill'] = entity.prefill # the other two cannot be prefilled
if target_type is flat.IntegrationQuestion:
data['integration_uuid'] = NULL_UUID
return target_type(uuid=entity.uuid, **data)
Expand Down
10 changes: 9 additions & 1 deletion packages/dsw-models/dsw/models/knowledge_model/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@
import pydantic

from ..common import Annotations, BaseModel, JsonValue, KeyValue, Timestamp
from .common import MetricMeasure, QuestionValidation, QuestionValueType, TypeHintExchange
from .common import (
MetricMeasure,
QuestionPrefill,
QuestionValidation,
QuestionValueType,
TypeHintExchange,
)


class EditEventField[T](BaseModel):
Expand Down Expand Up @@ -116,6 +122,7 @@ class AddQuestionEventContentBase(EventContent):
required_phase_uuid: UUID | None = None
annotations: Annotations
tag_uuids: list[UUID]
prefill: QuestionPrefill | None = None


class AddOptionsQuestionEventContent(AddQuestionEventContentBase):
Expand Down Expand Up @@ -174,6 +181,7 @@ class EditQuestionEventContentBase(EventContent):
tag_uuids: EditEventField[list[UUID]]
expert_uuids: EditEventField[list[UUID]]
reference_uuids: EditEventField[list[UUID]]
prefill: EditEventField[QuestionPrefill | None]


class EditOptionsQuestionEventContent(EditQuestionEventContentBase):
Expand Down
9 changes: 8 additions & 1 deletion packages/dsw-models/dsw/models/knowledge_model/flat.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@
import pydantic

from ..common import Annotations, BaseModel, JsonValue, KeyValue
from .common import MetricMeasure, QuestionValidation, QuestionValueType, TypeHintExchange
from .common import (
MetricMeasure,
QuestionPrefill,
QuestionValidation,
QuestionValueType,
TypeHintExchange,
)


class Entity(BaseModel):
Expand All @@ -28,6 +34,7 @@ class QuestionBase(Entity):
tag_uuids: list[UUID] = pydantic.Field(default_factory=list)
expert_uuids: list[UUID] = pydantic.Field(default_factory=list)
reference_uuids: list[UUID] = pydantic.Field(default_factory=list)
prefill: QuestionPrefill | None = None


class OptionsQuestion(QuestionBase):
Expand Down
5 changes: 4 additions & 1 deletion packages/dsw-models/dsw/models/knowledge_model/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def children(self) -> list[Node]:


class Question(Node):
__slots__ = ('experts', 'references', 'required_phase', 'tags')
__slots__ = ('experts', 'prefill_source', 'references', 'required_phase', 'tags')
kind = 'question'
entity: flat.QuestionBase

Expand All @@ -150,6 +150,9 @@ def _link(self) -> None:
'expertUuids', self.entity.expert_uuids, Expert)
self.references: list[Reference] = self._resolve(
'referenceUuids', self.entity.reference_uuids, Reference)
prefill = self.entity.prefill
self.prefill_source: Question | None = self._resolve_optional(
'prefill', prefill.source_question_uuid if prefill else None, Question)

@property
def question_type(self) -> str:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,21 @@ def step_19(event: typing.Any, ctx: MigrationContext) -> list[typing.Any]:
return [{**event, 'content': content}]


# 20 → 21: prefill of questions
def step_20(event: typing.Any, ctx: MigrationContext) -> list[typing.Any]:
if not isinstance(event, dict):
return [event]
content = event.get('content', {})
event_type = _event_type(content)
if event_type in ('AddQuestionEvent', 'EditQuestionEvent'):
prefill = None if event_type == 'AddQuestionEvent' else _unchanged()
event = {**event, 'content': {**content, 'prefill': prefill}}
return [event]


STEPS: dict[int, Step] = {
1: step_01, 2: step_02, 3: step_03, 4: step_noop, 5: step_noop, 6: step_06, 7: step_07,
8: step_08, 9: step_09, 10: step_10, 11: step_11, 12: step_noop, 13: step_noop, 14: step_14,
15: step_noop, 16: step_16, 17: step_17, 18: step_18, 19: step_19,
20: step_20,
}
3 changes: 2 additions & 1 deletion packages/dsw-models/dsw/models/knowledge_model/squash.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ class _Rules(typing.NamedTuple):
reorder: typing.Literal['never', 'same_entity', 'always']


_QUESTION_BLOCKING = ('required_phase_uuid', 'tag_uuids', 'expert_uuids', 'reference_uuids')
_QUESTION_BLOCKING = ('required_phase_uuid', 'tag_uuids', 'expert_uuids', 'reference_uuids',
'prefill')
_QUESTION_SAME_ENTITY = ('tag_uuids', 'expert_uuids', 'reference_uuids')
_NONE: frozenset[str] = frozenset()

Expand Down
3 changes: 2 additions & 1 deletion packages/dsw-models/dsw/models/knowledge_model/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from ..common import Annotations, BaseModel
from . import flat
from .common import MetricMeasure, QuestionValidation, QuestionValueType
from .common import MetricMeasure, QuestionPrefill, QuestionValidation, QuestionValueType


class Entity(BaseModel):
Expand Down Expand Up @@ -52,6 +52,7 @@ class QuestionBase(Entity):
tag_uuids: list[UUID] = pydantic.Field(default_factory=list)
experts: list[Expert] = pydantic.Field(default_factory=list)
references: list[Reference] = pydantic.Field(default_factory=list)
prefill: QuestionPrefill | None = None


class Answer(Entity):
Expand Down
Loading
Loading