diff --git a/plugin/src/client.ts b/plugin/src/client.ts index 9161d52..6bae207 100644 --- a/plugin/src/client.ts +++ b/plugin/src/client.ts @@ -8,6 +8,7 @@ import type { LlmSettingsUpdate, PipelineStatusResponse, PipelineSummaryItem, + QuestionnaireChangesResponse, TemplateDetail, TemplateOption, TemplateScope, @@ -243,6 +244,31 @@ export const getLatestQuestionnaireEventUuid = async ( return latest.uuid } +export const getQuestionnaireChanges = async ( + runId: string, +): Promise => { + const url = `${getApiBaseUrl()}/pipelines/status/${encodeURIComponent(runId)}/changes` + const response = await apiFetch(url) + const data = await readApiResponse( + response, + url, + ) + + if (!response.ok) { + throw new Error( + 'detail' in data && data.detail + ? data.detail + : 'Failed to load the changes of the questionnaire.', + ) + } + + if (!('tree' in data) || !Array.isArray(data.tree)) { + throw new Error('Invalid questionnaire changes returned.') + } + + return data +} + export const deletePipeline = async (runId: string): Promise => { const url = `${getApiBaseUrl()}/pipelines/status/${encodeURIComponent(runId)}` const response = await apiFetch(url, { method: 'DELETE' }) diff --git a/plugin/src/components/Modal.module.css b/plugin/src/components/Modal.module.css index cc1ffea..9bb5cf6 100644 --- a/plugin/src/components/Modal.module.css +++ b/plugin/src/components/Modal.module.css @@ -26,6 +26,15 @@ color: var(--ui-text); } +/* The body takes the height the header and footer leave, so the dialog does not resize with its content. */ +.fullHeight { + height: calc(100vh - 3.5rem); +} + +.fullHeight .body { + flex: 1; +} + .content:focus { outline: none; } diff --git a/plugin/src/components/Modal.tsx b/plugin/src/components/Modal.tsx index 834ffe2..6668d94 100644 --- a/plugin/src/components/Modal.tsx +++ b/plugin/src/components/Modal.tsx @@ -16,6 +16,8 @@ type ModalProps = { initialFocusRef?: RefObject /** Blocks closing, e.g. while the content is being saved. */ closeDisabled?: boolean + /** As tall as the window allows the whole time, so content that grows or shrinks does not resize it. */ + fullHeight?: boolean } /** @@ -38,6 +40,7 @@ export function Modal({ busy, initialFocusRef, closeDisabled = false, + fullHeight = false, }: ModalProps) { return ( { diff --git a/plugin/src/components/QuestionnaireChangeBadge.tsx b/plugin/src/components/QuestionnaireChangeBadge.tsx deleted file mode 100644 index 0b67e77..0000000 --- a/plugin/src/components/QuestionnaireChangeBadge.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { Badge } from '@ds-wizard/plugin-sdk/ui/Badge' -import { Spinner } from '@ds-wizard/plugin-sdk/ui/Icon' - -import type { RunRecord } from '@/hooks/useGenerationHistory' -import { - isQuestionnaireChanged, - type LatestQuestionnaireEvent, -} from '@/hooks/useLatestQuestionnaireEvent' - -type QuestionnaireChangeBadgeProps = { - run: Pick - latestEvent: LatestQuestionnaireEvent -} - -/** A small badge saying whether the questionnaire answers may have changed since the document was generated. */ -export function QuestionnaireChangeBadge({ run, latestEvent }: QuestionnaireChangeBadgeProps) { - if (run.status !== 'succeeded') return null - - if (latestEvent.status === 'loading') { - return - } - - // Unchanged, or not verifiable (older run, DSW unreachable): nothing to show. - if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null - - return ( - - Questionnaire changed after the DMP was generated - - ) -} diff --git a/plugin/src/components/QuestionnaireChangeNote.module.css b/plugin/src/components/QuestionnaireChangeNote.module.css new file mode 100644 index 0000000..e6dbfcb --- /dev/null +++ b/plugin/src/components/QuestionnaireChangeNote.module.css @@ -0,0 +1,5 @@ +/* The alert's content fills the row, so the button can sit at the end. */ +.note :global(.ui-alert__content) { + flex: 1; + min-width: 0; +} diff --git a/plugin/src/components/QuestionnaireChangeNote.tsx b/plugin/src/components/QuestionnaireChangeNote.tsx new file mode 100644 index 0000000..d037f08 --- /dev/null +++ b/plugin/src/components/QuestionnaireChangeNote.tsx @@ -0,0 +1,46 @@ +import { Alert } from '@ds-wizard/plugin-sdk/ui/Alert' +import { Button } from '@ds-wizard/plugin-sdk/ui/Button' +import { Inline } from '@ds-wizard/plugin-sdk/ui/Layout' +import { useState } from 'react' + +import styles from '@/components/QuestionnaireChangeNote.module.css' +import { QuestionnaireChangesModal } from '@/components/QuestionnaireChangesModal' +import type { RunRecord } from '@/hooks/useGenerationHistory' +import { + isQuestionnaireChanged, + type LatestQuestionnaireEvent, +} from '@/hooks/useLatestQuestionnaireEvent' + +type QuestionnaireChangeNoteProps = { + run: Pick + latestEvent: LatestQuestionnaireEvent +} + +/** + * A note, shown when the questionnaire answers may have changed since the document was generated, that lists + * what changed when clicked. + */ +export function QuestionnaireChangeNote({ run, latestEvent }: QuestionnaireChangeNoteProps) { + const [isOpen, setIsOpen] = useState(false) + + if (run.status !== 'succeeded') return null + + // Still checking, unchanged, or not verifiable (older run, DSW unreachable): nothing to show. + if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null + + return ( + <> + + + DMP is outdated + + + + {isOpen && ( + setIsOpen(false)} /> + )} + + ) +} diff --git a/plugin/src/components/QuestionnaireChangesModal.module.css b/plugin/src/components/QuestionnaireChangesModal.module.css new file mode 100644 index 0000000..5a54cc4 --- /dev/null +++ b/plugin/src/components/QuestionnaireChangesModal.module.css @@ -0,0 +1,112 @@ +.tree { + --tree-indent: 1.25rem; + --tree-line: var(--ui-border-strong); + /* Where a line of text is cut by its connector, about the middle of the first line. */ + --tree-elbow: 0.75em; + + font-size: 0.875rem; + line-height: 1.5; +} + +.root, +.level { + margin: 0; + padding: 0; + list-style: none; +} + +/* Chapters start at the left edge; everything under them hangs off guide lines. */ +.level { + margin-left: 0.35rem; +} + +.level > .node { + position: relative; + padding-left: var(--tree-indent); +} + +/* The vertical guide, running down past every sibling but the last. */ +.level > .node::before { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 0; + border-left: 1px solid var(--tree-line); +} + +/* The last sibling's guide stops at its own connector, drawing an elbow. */ +.level > .node:last-child::before { + bottom: auto; + height: calc(var(--tree-elbow) + 0.15rem); +} + +/* The horizontal connector into the node's line. */ +.level > .node::after { + content: ''; + position: absolute; + top: calc(var(--tree-elbow) + 0.15rem); + left: 0; + width: calc(var(--tree-indent) - 0.35rem); + border-top: 1px solid var(--tree-line); +} + +.line { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.25rem var(--ui-space-2); + padding: 0.15rem 0; + overflow-wrap: anywhere; +} + +.root > .node + .node { + margin-top: var(--ui-space-2); +} + +.chapter { + font-weight: 700; +} + +.question { + font-weight: 600; +} + +.item { + color: var(--ui-text-muted); + font-style: italic; +} + +.values { + display: inline-flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.25rem var(--ui-space-2); + min-width: 0; +} + +.removed, +.added, +.answer { + padding: 0 0.25rem; + border-radius: var(--ui-radius-control); + white-space: pre-wrap; +} + +.removed { + background: var(--ui-danger-subtle); + color: var(--ui-danger-on-subtle); + text-decoration: line-through; +} + +.added { + background: var(--ui-success-subtle); + color: var(--ui-success-on-subtle); + text-decoration: none; +} + +/* The answer an unchanged options question has, which its changed follow-up questions follow from. */ +.answer { + background: var(--ui-surface-sunken); + color: var(--ui-text-muted); +} diff --git a/plugin/src/components/QuestionnaireChangesModal.tsx b/plugin/src/components/QuestionnaireChangesModal.tsx new file mode 100644 index 0000000..72e3c7c --- /dev/null +++ b/plugin/src/components/QuestionnaireChangesModal.tsx @@ -0,0 +1,169 @@ +import { Alert } from '@ds-wizard/plugin-sdk/ui/Alert' +import { AsyncBlock } from '@ds-wizard/plugin-sdk/ui/AsyncBlock' +import { Button } from '@ds-wizard/plugin-sdk/ui/Button' +import { Muted, VisuallyHidden } from '@ds-wizard/plugin-sdk/ui/Text' +import { useEffect, useState } from 'react' + +import { getQuestionnaireChanges } from '@/client' +import { Modal } from '@/components/Modal' +import styles from '@/components/QuestionnaireChangesModal.module.css' +import type { + QuestionnaireChangeNode, + QuestionnaireChangesResponse, + QuestionnaireValueChange, +} from '@/types' + +type QuestionnaireChangesModalProps = { + runId: string + onClose: () => void +} + +type LoadState = + | { status: 'loading' } + | { status: 'failed'; message: string } + | { status: 'ready'; data: QuestionnaireChangesResponse } + +const UNTITLED: Record = { + chapter: 'Untitled chapter', + question: 'Unknown question', + item: 'Untitled item', +} + +// Long answers are cut so a line of the tree stays short; the whole value is shown on hover. +const MAX_VALUE_LENGTH = 200 + +function shorten(value: string): string { + return value.length > MAX_VALUE_LENGTH ? `${value.slice(0, MAX_VALUE_LENGTH - 1)}…` : value +} + +/** The old value struck through in red and the current one in green, either left out when there is none. */ +function ChangeValues({ change }: { change: QuestionnaireValueChange }) { + return ( + + {change.oldValue && ( + + Removed: + {shorten(change.oldValue)} + + )} + {change.newValue && ( + + Added: + {shorten(change.newValue)} + + )} + + ) +} + +function TreeNode({ node }: { node: QuestionnaireChangeNode }) { + return ( +
  • +
    + {node.title ?? UNTITLED[node.kind]} + {node.change ? ( + + ) : ( + node.answer && ( + + Answer: + {node.answer} + + ) + )} +
    + {node.children.length > 0 && } +
  • + ) +} + +function TreeLevel({ nodes, root = false }: { nodes: QuestionnaireChangeNode[]; root?: boolean }) { + return ( +
      + {nodes.map((node) => ( + + ))} +
    + ) +} + +function ChangeTree({ tree }: { tree: QuestionnaireChangeNode[] }) { + return ( +
    + +
    + ) +} + +function ChangesContent({ data }: { data: QuestionnaireChangesResponse }) { + if (!data.available) { + return ( + + This document was generated before the answers were stored, so what changed cannot + be shown. + + ) + } + if (data.tree.length === 0) { + return ( + + No answers differ from when this document was generated. Only other parts of the + questionnaire, such as its phase or labels, were edited. + + ) + } + + return +} + +/** Lists the answers that differ between a generation and the questionnaire as it is now. */ +export function QuestionnaireChangesModal({ runId, onClose }: QuestionnaireChangesModalProps) { + const [state, setState] = useState({ status: 'loading' }) + + useEffect(() => { + let cancelled = false + setState({ status: 'loading' }) + void getQuestionnaireChanges(runId) + .then((data) => { + if (!cancelled) setState({ status: 'ready', data }) + }) + .catch((error: unknown) => { + if (!cancelled) { + setState({ + status: 'failed', + message: + error instanceof Error + ? error.message + : 'Failed to load the changes of the questionnaire.', + }) + } + }) + + return () => { + cancelled = true + } + }, [runId]) + + return ( + + Close + + } + > + + {state.status === 'ready' && } + + + ) +} diff --git a/plugin/src/components/RunDetailPanel.tsx b/plugin/src/components/RunDetailPanel.tsx index 1a40e74..d95d1d4 100644 --- a/plugin/src/components/RunDetailPanel.tsx +++ b/plugin/src/components/RunDetailPanel.tsx @@ -7,7 +7,7 @@ import { Muted, Title } from '@ds-wizard/plugin-sdk/ui/Text' import { useEffect, useState } from 'react' import { PipelineResultPanel } from '@/components/PipelineResultPanel' -import { QuestionnaireChangeBadge } from '@/components/QuestionnaireChangeBadge' +import { QuestionnaireChangeNote } from '@/components/QuestionnaireChangeNote' import styles from '@/components/RunDetailPanel.module.css' import { getRunTimeLabel, @@ -163,8 +163,8 @@ export function RunDetailPanel({ runId, history, latestEvent }: RunDetailPanelPr {getRunVersionLabel(run)} {getRunTimeLabel(run)} - + diff --git a/plugin/src/types.ts b/plugin/src/types.ts index 49fba1e..ccf0666 100644 --- a/plugin/src/types.ts +++ b/plugin/src/types.ts @@ -112,4 +112,29 @@ export type PipelineSummaryItem = { sourceEventUuid: string | null } +/** A reply that differs between a generation and the questionnaire now. */ +export type QuestionnaireValueChange = { + kind: 'added' | 'changed' | 'removed' + oldValue: string | null + newValue: string | null +} + +/** A chapter, question or list item with changes in it, in the questionnaire's order. */ +export type QuestionnaireChangeNode = { + path: string + kind: 'chapter' | 'question' | 'item' + title: string | null + /** The change of this node's own reply, if it changed. */ + change: QuestionnaireValueChange | null + /** The selected answer of an options question that did not change itself but has changed follow-ups. */ + answer: string | null + children: QuestionnaireChangeNode[] +} + +export type QuestionnaireChangesResponse = { + /** False for runs that did not store their answers, so there is nothing to compare with. */ + available: boolean + tree: QuestionnaireChangeNode[] +} + export type ResultRenderMode = 'formatted' | 'raw' diff --git a/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py b/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py index 7e60848..dcdcbeb 100644 --- a/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py +++ b/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py @@ -18,6 +18,7 @@ GenerationLLM, ) from ai_document_plugin_service.ai.generation.parse_answers import parse_answer +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies from ai_document_plugin_service.cover_page.cover_page_renderer import CoverPageRenderer from ai_document_plugin_service.cover_page.cover_page_resolvers import CoverDataSources @@ -88,7 +89,7 @@ async def run_async( ) cover_page_assignments = document_assignments[:cover_page_section_count] document_assignments = document_assignments[cover_page_section_count:] - replies = self._filter_reachable_replies(replies, km) + replies = reachable_replies(km, replies) logger.info( 'Starting DMP generation', extra={ @@ -241,129 +242,6 @@ def run( msg, ) - @staticmethod - def _filter_reachable_replies( - replies: dict[str, Any], - km: dict[str, Any], - ) -> dict[str, Any]: - """Keep only replies that are reachable in the current questionnaire state. - - DSW can keep stale descendants in the raw questionnaire JSON when a user - changes an earlier answer (for example `YES -> NO`) or removes a list - item. Generation should ignore those historical branches and only use - replies that can be reached from the current KM roots via the currently - selected option answers and existing list-item UUIDs. - """ - chapter_uuids = km.get('chapterUuids') - entities = km.get('entities', {}) - chapters = entities.get('chapters', {}) - questions = entities.get('questions', {}) - answers = entities.get('answers', {}) - if not chapter_uuids or not chapters or not questions: - return replies - - reachable_paths: set[str] = set() - - for chapter_uuid in chapter_uuids: - chapter = chapters.get(chapter_uuid) - if chapter is None: - continue - for question_uuid in chapter.get('questionUuids', []): - DmpGeneratorComponent._walk_reachable_question( - question_uuid, - f'{chapter_uuid}.{question_uuid}', - replies, - questions, - answers, - reachable_paths, - ) - - return {key: value for key, value in replies.items() if key in reachable_paths} - - @staticmethod - def _walk_reachable_options_question( - path: str, - replies: dict[str, Any], - answers: dict[str, Any], - ) -> list[tuple[str, str]]: - selected_answer_uuid = replies.get(path, {}).get('value', {}).get('value') - if not selected_answer_uuid: - return [] - - answer = answers.get(selected_answer_uuid) - if answer is None: - return [] - - return [ - ( - follow_up_uuid, - f'{path}.{selected_answer_uuid}.{follow_up_uuid}', - ) - for follow_up_uuid in answer.get('followUpUuids', []) - ] - - @staticmethod - def _walk_reachable_list_question( - question: dict[str, Any], - path: str, - replies: dict[str, Any], - ) -> list[tuple[str, str]]: - list_items = replies.get(path, {}).get('value', {}).get('value', []) - if not isinstance(list_items, list): - logger.warning('Expected list items at %s, got %s', path, type(list_items).__name__) - return [] - - return [ - ( - nested_question_uuid, - f'{path}.{item_uuid}.{nested_question_uuid}', - ) - for item_uuid in list_items - for nested_question_uuid in question.get('itemTemplateQuestionUuids', []) - ] - - @staticmethod - def _walk_reachable_question( - question_uuid: str, - path: str, - replies: dict[str, Any], - questions: dict[str, Any], - answers: dict[str, Any], - reachable_paths: set[str], - ) -> None: - question = questions.get(question_uuid) - if question is None: - return - - if path in replies: - reachable_paths.add(path) - - question_type = question.get('questionType') - if question_type == 'OptionsQuestion': - child_questions = DmpGeneratorComponent._walk_reachable_options_question( - path, - replies, - answers, - ) - elif question_type == 'ListQuestion': - child_questions = DmpGeneratorComponent._walk_reachable_list_question( - question, - path, - replies, - ) - else: - child_questions = [] - - for child_question_uuid, child_path in child_questions: - DmpGeneratorComponent._walk_reachable_question( - child_question_uuid, - child_path, - replies, - questions, - answers, - reachable_paths, - ) - @staticmethod def _get_reply_keys_at_level(replies: dict[str, Any], prefix: str) -> list[str]: """Return reply keys that are prefix + exactly one more segment (neighbouring replies).""" diff --git a/service/src/ai_document_plugin_service/ai/generation/parse_answers.py b/service/src/ai_document_plugin_service/ai/generation/parse_answers.py index 82a71ea..1f8fad1 100644 --- a/service/src/ai_document_plugin_service/ai/generation/parse_answers.py +++ b/service/src/ai_document_plugin_service/ai/generation/parse_answers.py @@ -3,6 +3,8 @@ import re from typing import Any +from ai_document_plugin_service.ai.knowledgemodel.list_items import find_list_path + logger = logging.getLogger(__name__) RAW_URL_PATTERN = re.compile(r'https?://[^\s)]+') @@ -125,11 +127,16 @@ def _parse_item_select_reply( if not list_question_uuid: return '' - parent_path = question_path.rsplit('.', 1)[0] - list_path_prefix = f'{parent_path}.{list_question_uuid}' + list_path = find_list_path( + list_question_uuid, + selected_item_uuid, + ((path, payload.get('value')) for path, payload in replies.items()), + ) + if list_path is None: + return '' for reply_path, reply_payload in replies.items(): - if not reply_path.startswith(f'{list_path_prefix}.{selected_item_uuid}.'): + if not reply_path.startswith(f'{list_path}.{selected_item_uuid}.'): continue reply_question_uuid = reply_path.rsplit('.', 1)[-1] diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py index cde1f61..a78f624 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py @@ -12,6 +12,9 @@ # Stands for "event 0" of a questionnaire without any events. NO_EVENTS_UUID = UUID(int=0) +# The questionnaire detail carries the whole knowledge model, which DSW can take several seconds to build. +DSW_REQUEST_TIMEOUT_SECONDS = 15 + def parse_latest_event_uuid(payload: object) -> UUID: """Read the newest event UUID from a ``/projects/{uuid}/events?size=1&sort=createdAt,desc`` response. @@ -53,7 +56,7 @@ async def get_questionnaire_detail(self, questionnaire_uuid: UUID) -> dict: headers['Authorization'] = f'Bearer {self.token}' try: - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(timeout=DSW_REQUEST_TIMEOUT_SECONDS) as client: response = await client.get(url, headers=headers) response.raise_for_status() except httpx.HTTPError: @@ -94,7 +97,7 @@ async def get_latest_event_uuid(self, project_uuid: str | UUID) -> UUID: headers['Authorization'] = f'Bearer {self.token}' try: - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(timeout=DSW_REQUEST_TIMEOUT_SECONDS) as client: response = await client.get(url, headers=headers, params={'size': 1, 'sort': 'createdAt,desc'}) response.raise_for_status() except httpx.HTTPError: @@ -119,7 +122,7 @@ async def get_project_versions(self, project_uuid: str | UUID) -> list[dict]: headers['Authorization'] = f'Bearer {self.token}' try: - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(timeout=DSW_REQUEST_TIMEOUT_SECONDS) as client: response = await client.get(url, headers=headers) response.raise_for_status() except httpx.HTTPError: diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/list_items.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/list_items.py new file mode 100644 index 0000000..84c38a3 --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/list_items.py @@ -0,0 +1,22 @@ +"""Finding the list an item-select reply points to.""" + +from collections.abc import Iterable + + +def find_list_path(list_question_uuid: str, item_uuid: str, replies: Iterable[tuple[str, object]]) -> str | None: + """The path of the reply to the list question that holds the item, or None when no list reply holds it. + + ``replies`` yields ``(path, value)`` with the value as DSW sends it (``{type, value}``). The list question can + be anywhere in the knowledge model, not only next to the item-select question, so its reply is found by the + list question's UUID at the end of its path and the item among its items. + """ + suffix = f'.{list_question_uuid}' + for path, value in replies: + if ( + path.endswith(suffix) + and isinstance(value, dict) + and value.get('type') == 'ItemListReply' + and item_uuid in (value.get('value') or []) + ): + return path + return None diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/parser_component.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/parser_component.py index e445077..f35100d 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/parser_component.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/parser_component.py @@ -3,7 +3,6 @@ from haystack import component -from ai_document_plugin_service.ai.generation.parse_answers import parse_integration_reply_value from ai_document_plugin_service.ai.knowledgemodel.types import ( Chapter, Choice, @@ -18,32 +17,27 @@ ) logger = logging.getLogger(__name__) -REPLY_PATH_PARTS_MIN_LENGTH = 2 -REPLY_PARENT_SEGMENT_INDEX = -2 @component class ParserComponent: + """Parses the knowledge model of a questionnaire detail into a question tree. Replies are not part of it.""" + def __init__(self) -> None: self.km: dict = {} @component.output_types(data=list[QuestionData]) def run(self, data: dict) -> dict[str, list[QuestionData]]: self.km = data['knowledgeModel'] - replies = data['replies'] logger.info( - 'Parsing knowledge model replies into question tree', - extra={ - 'chapter_count': len(self.km.get('chapterUuids', [])), - 'reply_count': len(replies), - }, + 'Parsing knowledge model into question tree', + extra={'chapter_count': len(self.km.get('chapterUuids', []))}, ) - top_level_questions: list[QuestionData] = [] - for chapter_dict in self._iterate_km_chapters(): - parsed_chapter = self.parse_chapter(chapter_dict['uuid'], replies) - top_level_questions.append(parsed_chapter) + top_level_questions: list[QuestionData] = [ + self.parse_chapter(chapter_dict['uuid']) for chapter_dict in self._iterate_km_chapters() + ] logger.info( - 'Finished parsing knowledge model replies', + 'Finished parsing knowledge model', extra={'chapter_count': len(top_level_questions)}, ) return {'data': top_level_questions} @@ -52,7 +46,7 @@ def _iterate_km_chapters(self) -> Iterator[dict]: for chapter_uuid in self.km['chapterUuids']: yield self.km['entities']['chapters'][chapter_uuid] - def parse_chapter(self, chapter_uuid: str, replies: dict) -> Chapter: + def parse_chapter(self, chapter_uuid: str) -> Chapter: """Parse a Chapter from the knowledge model.""" chapter_data = self.km['entities']['chapters'][chapter_uuid] @@ -70,7 +64,6 @@ def parse_chapter(self, chapter_uuid: str, replies: dict) -> Chapter: for question_uuid in chapter_data.get('questionUuids', []): parsed_question = self.parse_question( question_uuid, - replies, chapter.uuid + '.' + question_uuid, parent_question=chapter, ) @@ -88,7 +81,6 @@ def parse_choice(self, choice_uuid: str) -> Choice: def parse_options_answer( self, answer_uuid: str, - replies: dict, path: str, parent_question: OptionsQuestion | None = None, ) -> OptionsAnswer: @@ -108,7 +100,6 @@ def parse_options_answer( for question_uuid in answer_data.get('followUpUuids', []): parsed_question = self.parse_question( question_uuid, - replies, parent_question=None, parent_answer=answer, path=path + '.' + question_uuid, @@ -119,17 +110,16 @@ def parse_options_answer( answer.followup_questions = followup_questions return answer + @staticmethod def parse_value_question( - self, question_uuid: str, question: dict, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, ) -> ValueQuestion: """Parse a ValueQuestion from the knowledge model.""" - value_question = ValueQuestion( + return ValueQuestion( path=path, uuid=question_uuid, title=question['title'], @@ -138,29 +128,16 @@ def parse_value_question( parent_answer=parent_answer, ) - value_question.reply = self.get_value_reply(replies, path) - - return value_question - @staticmethod - def get_value_reply( - replies: dict, - path: str, - ) -> str: - """Get the reply for the question.""" - return replies.get(path, {}).get('value', {}).get('value', '') - def parse_integration_question( - self, question_uuid: str, question: dict, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, ) -> IntegrationQuestion: """Parse an IntegrationQuestion from the knowledge model.""" - integration_question = IntegrationQuestion( + return IntegrationQuestion( path=path, uuid=question_uuid, title=question['title'], @@ -169,27 +146,10 @@ def parse_integration_question( parent_answer=parent_answer, ) - integration_question.reply = self.get_integration_reply( - replies, - path, - ) - - return integration_question - - @staticmethod - def get_integration_reply( - replies: dict, - path: str, - ) -> str: - """Get the reply for the question.""" - answer = replies.get(path, {}).get('value', {}) - return parse_integration_reply_value(answer) - def parse_list_question( self, question_uuid: str, question: dict, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, @@ -208,7 +168,6 @@ def parse_list_question( for nested_question_uuid in question.get('itemTemplateQuestionUuids', []): parsed_question = self.parse_question( nested_question_uuid, - replies, path + '.*.' + nested_question_uuid, parent_question=list_question, ) @@ -222,7 +181,6 @@ def parse_options_question( self, question_uuid: str, question: dict, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, @@ -239,45 +197,22 @@ def parse_options_question( ) # Parse answers with this options question as parent - answers = [ - self.parse_options_answer( - answer_uuid, - replies, - path + '.' + answer_uuid, - parent_question=options_question, - ) + options_question.answers = [ + self.parse_options_answer(answer_uuid, path + '.' + answer_uuid, parent_question=options_question) for answer_uuid in question.get('answerUuids', []) ] - - options_question.answers = answers - - options_question.reply = self.get_option_reply( - replies, - path, - ) - return options_question - def get_option_reply( - self, - replies: dict, - path: str, - ) -> str: - """Get the reply for the question.""" - reply = replies.get(path, {}).get('value', {}).get('value', '') - return self.km.get('entities', {}).get('answers', {}).get(reply, {}).get('label', '') - def parse_multi_choice_question( self, question_uuid: str, question: dict, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, ) -> MultiChoiceQuestion: """Parse a MultiChoiceQuestion from the knowledge model.""" - multichoice_question = MultiChoiceQuestion( + return MultiChoiceQuestion( path=path, uuid=question_uuid, title=question['title'], @@ -287,35 +222,16 @@ def parse_multi_choice_question( parent_answer=parent_answer, ) - multichoice_question.reply = '\n'.join( - self.get_multichoice_reply(replies, path), - ) - - return multichoice_question - - def get_multichoice_reply( - self, - replies: dict, - path: str, - ) -> list[str]: - """Get the reply for the question.""" - reply_values = replies.get(path, {}).get('value', {}).get('value', '') - return [ - self.km.get('entities', {}).get('answers', {}).get(reply_value, {}).get('label', '') - for reply_value in reply_values - ] - + @staticmethod def parse_item_select_question( - self, question_uuid: str, question: dict, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, ) -> ItemSelectQuestion: """Parse an ItemSelectQuestion from the knowledge model.""" - item_select_question = ItemSelectQuestion( + return ItemSelectQuestion( path=path, uuid=question_uuid, title=question['title'], @@ -324,52 +240,9 @@ def parse_item_select_question( parent_answer=parent_answer, ) - item_select_question.reply = self.get_item_select_question_reply(replies, path) - - return item_select_question - - def get_item_select_question_reply( - self, - replies: dict, - path: str, - ) -> str: - """Get the reply for the question.""" - selected_item_uuid = replies.get(path, {}).get('value', {}).get('value', '') - if not selected_item_uuid: - return '' - - list_path_prefix = path.split('.*.', maxsplit=1)[0] if '.*.' in path else path.rsplit('.', 1)[0] - - for reply_path, reply_payload in replies.items(): - path_parts = reply_path.split('.') - if len(path_parts) < REPLY_PATH_PARTS_MIN_LENGTH or path_parts[REPLY_PARENT_SEGMENT_INDEX] != 'reply': - continue - if not reply_path.startswith(f'{list_path_prefix}.'): - continue - if selected_item_uuid not in path_parts: - continue - - question_uuid = path_parts[-1] - question_type = self.km.get('entities', {}).get('questions', {}).get(question_uuid, {}).get('questionType') - - if question_type == 'ValueQuestion': - value = reply_payload.get('value', {}).get('value', '') - if value: - return value - continue - - if question_type == 'IntegrationQuestion': - answer = reply_payload.get('value', {}) - value = parse_integration_reply_value(answer) - if value: - return value - - return '' - def parse_question( self, question_uuid: str, - replies: dict, path: str, parent_question: QuestionData | None = None, parent_answer: OptionsAnswer | None = None, @@ -401,14 +274,7 @@ def parse_question( parser = parser_by_type.get(question_type) if parser is not None: - return parser( - question_uuid, - question, - replies, - path, - parent_question, - parent_answer, - ) + return parser(question_uuid, question, path, parent_question, parent_answer) if question_type == 'FileQuestion': logger.info('Skipping unsupported question type %s for question %s', question_type, question_uuid) return None diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py new file mode 100644 index 0000000..a530ee7 --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py @@ -0,0 +1,263 @@ +"""What changed between the replies stored with a generation and the replies of the questionnaire now.""" + +from collections.abc import Iterable, Iterator, Mapping +from dataclasses import dataclass +from enum import StrEnum +from itertools import starmap +from typing import Any + +from ai_document_plugin_service.ai.knowledgemodel.list_items import find_list_path +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( + StoredReply, + build_snapshot, + entity_label, +) +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import child_questions + +MAX_ITEM_TITLE_LENGTH = 80 +REMOVED_OPTION = '(removed option)' +NO_LONGER_IN_QUESTIONNAIRE = 'No longer in the questionnaire' + + +class ChangeKind(StrEnum): + ADDED = 'added' + CHANGED = 'changed' + REMOVED = 'removed' + + +@dataclass(frozen=True) +class ReplyChange: + path: str + kind: ChangeKind + old: StoredReply | None + new: StoredReply | None + + +class NodeKind(StrEnum): + CHAPTER = 'chapter' + QUESTION = 'question' + ITEM = 'item' + + +@dataclass(frozen=True) +class ValueChange: + """A changed reply in words, as shown to the user.""" + + kind: ChangeKind + old_value: str | None + new_value: str | None + + +@dataclass(frozen=True) +class ChangeNode: + """A chapter, question or list item of the questionnaire with changes in it, in the questionnaire's order.""" + + path: str + kind: NodeKind + title: str | None + # The change of this node's own reply, e.g. the items of a list when some of them changed too. + change: ValueChange | None = None + # For an options question that did not change itself but has changed follow-up questions: the selected answer. + # When the answer did change, the follow-ups of the old answer are all removed and those of the new one added, + # so the change says which answer each belongs to. + answer: str | None = None + children: tuple['ChangeNode', ...] = () + + +def diff_replies(old: Iterable[StoredReply], new: Iterable[StoredReply]) -> list[ReplyChange]: + """The replies added, changed and removed between two snapshots, ordered by path.""" + old_by_path = {reply.path: reply for reply in old} + new_by_path = {reply.path: reply for reply in new} + + changes: list[ReplyChange] = [] + for path in sorted(old_by_path.keys() | new_by_path.keys()): + before = old_by_path.get(path) + after = new_by_path.get(path) + if before is None: + changes.append(ReplyChange(path, ChangeKind.ADDED, None, after)) + elif after is None: + changes.append(ReplyChange(path, ChangeKind.REMOVED, before, None)) + elif not before.same_value_as(after): + changes.append(ReplyChange(path, ChangeKind.CHANGED, before, after)) + return changes + + +def change_tree(stored: Iterable[StoredReply], current_detail: dict[str, Any]) -> list[ChangeNode]: + """The changes between ``stored`` and the questionnaire detail as DSW returns it now, as a tree. + + What changed is what ``diff_replies`` says. Where each change goes comes from walking the current knowledge + model, following the stored and the current replies together, so the tree has the questionnaire's order: the + follow-up questions of both the old and the new answer sit under their question, and the questions of both + deleted and added items under the list. A change the walk does not reach, e.g. the reply to a question the + knowledge model no longer has, goes into a last group of its own. + + Labels and titles come from the current knowledge model; answers and choices it no longer knows fall back to + the label stored with the reply. + """ + km = current_detail['knowledgeModel'] + old = {reply.path: reply for reply in stored} + current = build_snapshot(km, current_detail['replies']) + new = {reply.path: reply for reply in current} + walk = _Walk(km, old, new, {change.path: change for change in diff_replies(old.values(), current)}) + + tree = [node for chapter_uuid in km['chapterUuids'] if (node := walk.chapter(chapter_uuid)) is not None] + placed = {node.path for node in _all_nodes(tree) if node.change is not None} + unplaced = tuple( + ChangeNode(path, NodeKind.QUESTION, _question_title(km, path), change=walk.value_change(change)) + for path, change in walk.changes.items() + if path not in placed + ) + if unplaced: + tree.append(ChangeNode('', NodeKind.CHAPTER, NO_LONGER_IN_QUESTIONNAIRE, children=unplaced)) + return tree + + +@dataclass(frozen=True) +class _Walk: + km: dict[str, Any] + old: Mapping[str, StoredReply] + new: Mapping[str, StoredReply] + changes: Mapping[str, ReplyChange] + + def chapter(self, chapter_uuid: str) -> ChangeNode | None: + chapter = self.km['entities']['chapters'].get(chapter_uuid, {}) + question_uuids = chapter.get('questionUuids', []) + children = self._question_nodes((uuid, f'{chapter_uuid}.{uuid}') for uuid in question_uuids) + return ChangeNode(chapter_uuid, NodeKind.CHAPTER, chapter.get('title'), children=children) if children else None + + def _question_nodes(self, questions: Iterable[tuple[str, str]]) -> tuple[ChangeNode, ...]: + nodes = starmap(self._question, questions) + return tuple(node for node in nodes if node is not None) + + def _question(self, question_uuid: str, path: str) -> ChangeNode | None: + """The question with the changes under it, or None when nothing in it changed.""" + entities = self.km['entities'] + question = entities['questions'].get(question_uuid) + if question is None: + return None + + # What is under the question with the old reply and with the new one, e.g. the follow-ups of both answers. + old, new = self.old.get(path), self.new.get(path) + below = child_questions(entities, question, path, old.value if old else None) + below += child_questions(entities, question, path, new.value if new else None) + children = self._question_nodes(dict.fromkeys(below)) + if question.get('questionType') == 'ListQuestion': + children = self._items(path, children) + + change = self.changes.get(path) + if change is None and not children: + return None + return ChangeNode( + path, + NodeKind.QUESTION, + question.get('title'), + change=self.value_change(change) if change else None, + answer=None if change else self._answer(new), + children=children, + ) + + def _items(self, list_path: str, questions: tuple[ChangeNode, ...]) -> tuple[ChangeNode, ...]: + """The changed questions of a list grouped by the item they belong to.""" + by_item: dict[str, list[ChangeNode]] = {} + for node in questions: + by_item.setdefault(node.path[len(list_path) + 1 :].split('.', 1)[0], []).append(node) + current_items = _strings(self.new[list_path].raw) if list_path in self.new else [] + return tuple( + ChangeNode( + f'{list_path}.{item_uuid}', + NodeKind.ITEM, + _item_title(self.km, list_path, item_uuid, self.new if item_uuid in current_items else self.old), + children=tuple(nodes), + ) + for item_uuid, nodes in by_item.items() + ) + + def _answer(self, reply: StoredReply | None) -> str | None: + """The label of the answer an options reply selects.""" + if reply is None or reply.reply_type != 'AnswerReply': + return None + return _answer_label(reply, self.km) + + def value_change(self, change: ReplyChange) -> ValueChange: + return ValueChange( + kind=change.kind, + old_value=_describe_value(change.old, self.km, self.old) if change.old is not None else None, + new_value=_describe_value(change.new, self.km, self.new) if change.new is not None else None, + ) + + +def _all_nodes(nodes: Iterable[ChangeNode]) -> Iterator[ChangeNode]: + for node in nodes: + yield node + yield from _all_nodes(node.children) + + +def _questions(km: dict[str, Any]) -> dict[str, Any]: + return km['entities']['questions'] + + +def _question_title(km: dict[str, Any], path: str) -> str | None: + return _questions(km).get(path.rsplit('.', 1)[-1], {}).get('title') + + +def _item_title(km: dict[str, Any], list_path: str, item_uuid: str, side: Mapping[str, StoredReply]) -> str: + """An item has no title of its own: it is the answer to the first question of the list's item template.""" + list_question = _questions(km).get(list_path.rsplit('.', 1)[-1], {}) + templates = list_question.get('itemTemplateQuestionUuids', []) + if templates: + first = side.get(f'{list_path}.{item_uuid}.{templates[0]}') + text = _text(first) if first is not None else None + if text and text.strip(): + title = text.strip().splitlines()[0] + if len(title) > MAX_ITEM_TITLE_LENGTH: + return title[: MAX_ITEM_TITLE_LENGTH - 1] + '…' + return title + return 'Untitled item' + + +def _answer_label(reply: StoredReply, km: dict[str, Any]) -> str: + return entity_label(km['entities'], 'answers', reply.raw) or reply.display_text or REMOVED_OPTION + + +def _strings(raw: object) -> list[str]: + """The UUIDs of a multi-choice or item-list reply.""" + return [value for value in raw if isinstance(value, str)] if isinstance(raw, list) else [] + + +def _text(reply: StoredReply) -> str | None: + """The text of a string reply, or the text an integration reply shows.""" + raw = reply.raw + if reply.reply_type == 'IntegrationReply' and isinstance(raw, dict): + raw = raw.get('value') + return raw if isinstance(raw, str) else None + + +def _describe_value(reply: StoredReply, km: dict[str, Any], side: Mapping[str, StoredReply]) -> str: + if reply.reply_type == 'AnswerReply': + return _answer_label(reply, km) + if reply.reply_type == 'MultiChoiceReply': + return _describe_choices(reply, km) + if reply.reply_type == 'ItemSelectReply': + return _describe_selected_item(reply, km, side) + if reply.reply_type == 'ItemListReply': + return ', '.join(_item_title(km, reply.path, item_uuid, side) for item_uuid in _strings(reply.raw)) + return _text(reply) or '' + + +def _describe_choices(reply: StoredReply, km: dict[str, Any]) -> str: + labels = [entity_label(km['entities'], 'choices', choice) for choice in _strings(reply.raw)] + if labels and all(labels): + return ', '.join(label for label in labels if label) + return reply.display_text or REMOVED_OPTION + + +def _describe_selected_item(reply: StoredReply, km: dict[str, Any], side: Mapping[str, StoredReply]) -> str: + """An item-select reply names an item of another list; its title is looked up there.""" + question = _questions(km).get(reply.path.rsplit('.', 1)[-1], {}) + list_question_uuid = question.get('listQuestionUuid') + if not list_question_uuid or not isinstance(reply.raw, str): + return 'Untitled item' + list_path = find_list_path(list_question_uuid, reply.raw, ((path, r.value) for path, r in side.items())) + if list_path is None: + return 'Untitled item' + return _item_title(km, list_path, reply.raw, side) diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py new file mode 100644 index 0000000..f7056cf --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py @@ -0,0 +1,98 @@ +"""The replies of a questionnaire in the form they are stored with a generation. + +Only replies that apply to the questionnaire as it stands are kept (see ``reachable_replies``), each with its value +exactly as DSW sends it (``{type, value}``), so that anything in a reply that can reach the document is compared. +Replies that are empty, and replies of types that never reach a document (files), are left out, so that an empty +reply and a missing one are the same thing when two snapshots are compared. +""" + +import logging +from dataclasses import dataclass +from typing import Any + +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies + +logger = logging.getLogger(__name__) + +# Reply types whose value never reaches a document. +_LEFT_OUT_REPLY_TYPES = frozenset({'FileReply'}) + + +@dataclass(frozen=True) +class StoredReply: + """One reply.""" + + path: str + # The value of the reply as DSW sends it, e.g. ``{'type': 'AnswerReply', 'value': ''}``. + value: dict[str, Any] + # What the value was called when it was stored, for answers and choices whose label can no longer be looked + # up later, e.g. after the knowledge model changed. Not part of the value. + display_text: str | None = None + + @property + def reply_type(self) -> str | None: + reply_type = self.value.get('type') + return reply_type if isinstance(reply_type, str) else None + + @property + def raw(self) -> object: + """The ``value`` inside the value: text, a UUID, a list of UUIDs or, for integrations, a mapping.""" + return self.value.get('value') + + def same_value_as(self, other: 'StoredReply') -> bool: + return self.value == other.value + + +def build_snapshot(km: dict[str, Any], replies: dict[str, Any]) -> list[StoredReply]: + """The reachable replies of a questionnaire, ordered by path. + + ``km`` is the ``knowledgeModel`` of the questionnaire detail and ``replies`` its ``replies``. A reply without + a typed value is skipped with a warning instead of failing the caller. + """ + entities = km['entities'] + snapshot: list[StoredReply] = [] + for path, reply in sorted(reachable_replies(km, replies).items()): + value = reply.get('value') + if not isinstance(value, dict) or not isinstance(value.get('type'), str): + logger.warning('Skipping a reply without a typed value', extra={'reply_path': path}) + continue + if value['type'] in _LEFT_OUT_REPLY_TYPES or _is_empty(value): + continue + snapshot.append(StoredReply(path, value, _display_text(value, entities))) + return snapshot + + +def _is_empty(value: dict[str, Any]) -> bool: + raw = value.get('value') + if value['type'] == 'IntegrationReply' and isinstance(raw, dict): + # ``{type, value, raw?}``: empty when it has neither text nor a record. + return _is_blank(raw.get('value')) and not raw.get('raw') + return _is_blank(raw) + + +def _is_blank(raw: object) -> bool: + if raw is None: + return True + if isinstance(raw, str): + return not raw.strip() + if isinstance(raw, (list, dict)): + return not raw + return False + + +def _display_text(value: dict[str, Any], entities: dict[str, Any]) -> str | None: + reply_type, raw = value['type'], value.get('value') + if reply_type == 'AnswerReply' and isinstance(raw, str): + return entity_label(entities, 'answers', raw) + if reply_type == 'MultiChoiceReply' and isinstance(raw, list): + labels = [entity_label(entities, 'choices', choice) for choice in raw] + return ', '.join(label for label in labels if label) or None + return None + + +def entity_label(entities: dict[str, Any], kind: str, uuid: object) -> str | None: + """The label of an answer or choice in the knowledge model, or None when it has none (any more).""" + if not isinstance(uuid, str): + return None + label = entities.get(kind, {}).get(uuid, {}).get('label') + return label if isinstance(label, str) else None diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py new file mode 100644 index 0000000..f8123af --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py @@ -0,0 +1,70 @@ +""" +Filter questionnaire replies down to those that apply to the questionnaire as it stands. + +DSW keeps replies that no longer apply: after an options question is switched to another answer, the replies to +the follow-up questions of the previous answer stay in the data. This walks the knowledge model from the +chapters and keeps only the replies on a path that the other replies lead to. +""" + +from typing import Any + + +def reachable_replies(km: dict[str, Any], replies: dict[str, Any]) -> dict[str, Any]: + """Return the replies that apply to the questionnaire, keyed by their path and otherwise untouched. + + ``km`` is the ``knowledgeModel`` of the questionnaire detail and ``replies`` its ``replies``. A reply is kept + when its question exists in the knowledge model and every option answer and list item on its path is the one + currently selected. An item-select reply whose item has since been deleted is kept as it is; it is a reply of + a reachable question. + + The replies keep the order of ``replies``: document generation takes the order of list items from it. + """ + entities = km['entities'] + reachable: set[str] = set() + + stack: list[tuple[str, str]] = [] + for chapter_uuid in km['chapterUuids']: + chapter = entities['chapters'].get(chapter_uuid, {}) + stack.extend( + (question_uuid, f'{chapter_uuid}.{question_uuid}') for question_uuid in chapter.get('questionUuids', []) + ) + + while stack: + question_uuid, path = stack.pop() + question = entities['questions'].get(question_uuid) + if question is None: + continue + reply = replies.get(path) + if reply is not None: + reachable.add(path) + stack.extend(child_questions(entities, question, path, reply.get('value') if reply is not None else None)) + + return {path: reply for path, reply in replies.items() if path in reachable} + + +def child_questions( + entities: dict[str, Any], + question: dict[str, Any], + path: str, + value: dict[str, Any] | None, +) -> list[tuple[str, str]]: + """The questions below a question as ``(question uuid, path)``, given the value of the reply to it. + + ``value`` is the reply's value as DSW sends it (``{type, value}``), or None when there is no reply. + """ + value = value or {} + question_type = question.get('questionType') + + if question_type == 'OptionsQuestion' and value.get('type') == 'AnswerReply': + answer_uuid = value['value'] + answer = entities['answers'].get(answer_uuid, {}) + return [(follow_up, f'{path}.{answer_uuid}.{follow_up}') for follow_up in answer.get('followUpUuids', [])] + + if question_type == 'ListQuestion' and value.get('type') == 'ItemListReply': + return [ + (template_question, f'{path}.{item_uuid}.{template_question}') + for item_uuid in value['value'] + for template_question in question.get('itemTemplateQuestionUuids', []) + ] + + return [] diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/types.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/types.py index 86dfc7f..902b70f 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/types.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/types.py @@ -20,7 +20,6 @@ def __init__( text: str | None, parent_question: Optional['QuestionData'] = None, parent_answer: Optional['OptionsAnswer'] = None, - reply: str | None = None, ) -> None: self.path = path self.uuid = uuid @@ -28,7 +27,6 @@ def __init__( self.text = text self.parent_question = parent_question self.parent_answer = parent_answer - self.reply = reply self.context: str | None = None @abstractmethod diff --git a/service/src/ai_document_plugin_service/ai/persistence/database.py b/service/src/ai_document_plugin_service/ai/persistence/database.py index 1f04689..e335cac 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/database.py +++ b/service/src/ai_document_plugin_service/ai/persistence/database.py @@ -18,6 +18,7 @@ from ai_document_plugin_service.ai.assignment.types import SectionQuestionPaths from ai_document_plugin_service.ai.common.config import DatabaseConfig, LLMConfig from ai_document_plugin_service.ai.common.types import TemplateContent +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply from ai_document_plugin_service.ai.persistence.errors import TemplateTitleConflictError from ai_document_plugin_service.ai.persistence.schema import create_persistence_schema from ai_document_plugin_service.ai.persistence.secret_cipher import SecretCipher @@ -271,6 +272,14 @@ async def create_generation_stats( ) -> None: """Create the stats row of a finished generation.""" + @abstractmethod + async def save_generation_replies(self, run_id: UUID, replies: Sequence[StoredReply]) -> None: + """Store the replies a generation was made from.""" + + @abstractmethod + async def get_generation_replies(self, run_id: UUID) -> list[StoredReply]: + """Get the replies stored with a generation, ordered by path. The caller checks ownership of the run.""" + @abstractmethod async def get_generation( self, @@ -322,6 +331,7 @@ def __init__( self.template_table = schema.template_table self.generation_table = schema.generation_table self.generation_stats_table = schema.generation_stats_table + self.generation_reply_table = schema.generation_reply_table self.llm_settings_table = schema.llm_settings_table self._database_verified = False logger.info( @@ -393,6 +403,7 @@ async def _ensure_schema(self) -> None: 'assignment_section', 'generation', 'generation_stats', + 'generation_reply', 'llm_settings', } missing_tables = sorted(required_tables - existing_tables) @@ -803,6 +814,37 @@ async def create_generation_stats( async with self._connect() as connection: await connection.execute(statement) + async def save_generation_replies(self, run_id: UUID, replies: Sequence[StoredReply]) -> None: + if not replies: + return + await self._ensure_schema() + rows = [ + { + 'run_id': run_id, + 'path': reply.path, + 'value': reply.value, + 'display_text': reply.display_text, + } + for reply in replies + ] + + async with self._connect() as connection: + await connection.execute(self.generation_reply_table.insert(), rows) + + async def get_generation_replies(self, run_id: UUID) -> list[StoredReply]: + await self._ensure_schema() + table = self.generation_reply_table + statement = select(table).where(table.c.run_id == run_id).order_by(table.c.path) + + async with self._connect() as connection: + result = await connection.execute(statement) + rows = result.fetchall() + + return [ + StoredReply(path=row.path, value=row.value, display_text=row.display_text) + for row in rows + ] + async def get_generation( self, run_id: UUID, diff --git a/service/src/ai_document_plugin_service/ai/persistence/schema.py b/service/src/ai_document_plugin_service/ai/persistence/schema.py index e770e8a..fb618f7 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/schema.py +++ b/service/src/ai_document_plugin_service/ai/persistence/schema.py @@ -14,7 +14,7 @@ func, text, ) -from sqlalchemy.dialects.postgresql import ARRAY, UUID +from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID @dataclass(frozen=True) @@ -25,6 +25,7 @@ class PersistenceSchema: template_table: Table generation_table: Table generation_stats_table: Table + generation_reply_table: Table llm_settings_table: Table @@ -117,7 +118,7 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: Column('result_markdown', Text, nullable=True), Column('progress_message', Text, nullable=True), Column('named_version', Text, nullable=True), - # Newest DSW event of the questionnaire when the run read it (see QuestionnaireStateService). + # Newest DSW event of the questionnaire when the run read it (see DSWClient.get_latest_event_uuid). # The nil UUID for a questionnaire without events; NULL for runs from before this column existed. Column('source_event_uuid', UUID(as_uuid=True), nullable=True), Column( @@ -165,6 +166,19 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: ), ) + # The replies a generation was made from, one row per reply (see questionnaire_snapshot). Written together with + # the generation succeeding; a generation without rows predates this table or had no replies, and the former + # is told by generation.source_event_uuid being NULL. + generation_reply_table = Table( + 'generation_reply', + metadata, + Column('run_id', UUID(as_uuid=True), ForeignKey('generation.run_id', ondelete='CASCADE'), primary_key=True), + Column('path', Text, primary_key=True), + # The value of the reply as DSW sends it (``{type, value}``), see StoredReply. + Column('value', JSONB, nullable=False), + Column('display_text', Text, nullable=True), + ) + # LLM connection settings, one row per tenant. Managed by tenant administrators. llm_settings_table = Table( 'llm_settings', @@ -192,5 +206,6 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: template_table=template_table, generation_table=generation_table, generation_stats_table=generation_stats_table, + generation_reply_table=generation_reply_table, llm_settings_table=llm_settings_table, ) diff --git a/service/src/ai_document_plugin_service/ai/run_pipeline.py b/service/src/ai_document_plugin_service/ai/run_pipeline.py index 2ec10d2..d24ee27 100644 --- a/service/src/ai_document_plugin_service/ai/run_pipeline.py +++ b/service/src/ai_document_plugin_service/ai/run_pipeline.py @@ -25,6 +25,7 @@ from ai_document_plugin_service.ai.generation.dmp_generator_component import DmpGeneratorComponent from ai_document_plugin_service.ai.generation.llm import SectionGenerationLLM from ai_document_plugin_service.ai.knowledgemodel.parser_component import ParserComponent +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot from ai_document_plugin_service.ai.persistence.assignment_loader_component import AssignmentLoaderComponent from ai_document_plugin_service.ai.persistence.assignment_saver_component import ( AssignmentSaverComponent, @@ -56,6 +57,8 @@ class PipelineOutput: # Generator output before polishing (the text fed into the polisher). dmp_pre_polished: str stats: PipelineStats + # The replies the document was generated from, kept to tell later what changed in the questionnaire. + reply_snapshot: tuple[StoredReply, ...] = () @dataclass(frozen=True) @@ -252,6 +255,7 @@ async def run_pipeline( markdown=result_markdown, dmp_pre_polished=dmp_pre_polished, stats=pipeline_stats, + reply_snapshot=tuple(build_snapshot(km, replies)), ) diff --git a/service/src/ai_document_plugin_service/api/pipeline_routes.py b/service/src/ai_document_plugin_service/api/pipeline_routes.py index f8b6340..17555b5 100644 --- a/service/src/ai_document_plugin_service/api/pipeline_routes.py +++ b/service/src/ai_document_plugin_service/api/pipeline_routes.py @@ -12,6 +12,7 @@ PipelineSaveRequest, PipelineStatusResponse, PipelineSummaryResponse, + QuestionnaireChangesResponse, ) from ai_document_plugin_service.di import ( AuthenticatedDI, @@ -72,6 +73,15 @@ async def get_pipeline_status( return status +@pipeline_router.get('/pipelines/status/{run_id}/changes') +async def get_questionnaire_changes( + run_id: UUID, + pipeline: PipelineServiceDI, + auth: AuthenticatedDI, +) -> QuestionnaireChangesResponse: + return await pipeline.get_questionnaire_changes(run_id, auth) + + @pipeline_router.patch('/pipelines/status/{run_id}/title') async def rename_pipeline_title( run_id: UUID, payload: PipelineRenameRequest, pipeline: PipelineServiceDI, auth: AuthenticatedDI diff --git a/service/src/ai_document_plugin_service/api/types.py b/service/src/ai_document_plugin_service/api/types.py index 0a9e899..c9bceb8 100644 --- a/service/src/ai_document_plugin_service/api/types.py +++ b/service/src/ai_document_plugin_service/api/types.py @@ -1,5 +1,5 @@ from enum import StrEnum -from typing import TYPE_CHECKING, Annotated, Self +from typing import TYPE_CHECKING, Annotated, Literal, Self from uuid import UUID from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -268,6 +268,33 @@ class PipelineErrorResponse(ApiModel): message: str +class QuestionnaireValueChangeResponse(ApiModel): + """A reply that differs between the generation and the questionnaire now.""" + + kind: Literal['added', 'changed', 'removed'] + old_value: str | None = None + new_value: str | None = None + + +class QuestionnaireChangeNodeResponse(ApiModel): + """A chapter, question or list item with changes in it, in the questionnaire's order.""" + + path: str + kind: Literal['chapter', 'question', 'item'] + title: str | None = None + # The change of this node's own reply, if it changed. + change: QuestionnaireValueChangeResponse | None = None + # The selected answer of an options question that did not change itself but has changed follow-ups. + answer: str | None = None + children: list['QuestionnaireChangeNodeResponse'] + + +class QuestionnaireChangesResponse(ApiModel): + # False for generations that did not store their replies, so there is nothing to compare with. + available: bool + tree: list[QuestionnaireChangeNodeResponse] + + class PipelineSummaryResponse(ApiModel): run_id: UUID template_uuid: UUID diff --git a/service/src/ai_document_plugin_service/di.py b/service/src/ai_document_plugin_service/di.py index 60f1794..76d64b6 100644 --- a/service/src/ai_document_plugin_service/di.py +++ b/service/src/ai_document_plugin_service/di.py @@ -10,7 +10,6 @@ from ai_document_plugin_service.service.llm_settings_service import LlmSettingsService from ai_document_plugin_service.service.pipeline_queue_manager import PipelineQueueManager from ai_document_plugin_service.service.pipeline_service import PipelineService -from ai_document_plugin_service.service.questionnaire_state_service import QuestionnaireStateService from ai_document_plugin_service.service.template_service import TemplateService @@ -20,11 +19,7 @@ def setup_app_state(app: fastapi.FastAPI, config: Config) -> None: app.state.template_service = TemplateService(app.state.database, config.cover_definition) app.state.llm_settings_service = LlmSettingsService(app.state.database) app.state.pipeline_queue_manager = PipelineQueueManager(config.max_parallel_executions) - app.state.pipeline_service = PipelineService( - app.state.pipeline_queue_manager, - app.state.database, - QuestionnaireStateService(), - ) + app.state.pipeline_service = PipelineService(app.state.pipeline_queue_manager, app.state.database) app.state.export_service = ExportService(app.state.database) diff --git a/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py b/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py new file mode 100644 index 0000000..5528bd1 --- /dev/null +++ b/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py @@ -0,0 +1,44 @@ +"""Store the replies a run was generated from. + +One row per reply with its value as DSW sends it (see questionnaire_snapshot), so that what changed in the +questionnaire since the run can be told. Existing runs have no rows; generation.source_event_uuid being NULL marks them. + +Revision ID: 20261120_02 +Revises: 20261120_01 +Create Date: 2026-11-20 00:00:00 +""" + +import sqlalchemy as sa +from alembic import context, op +from sqlalchemy.dialects import postgresql + +revision = '20261120_02' +down_revision = '20261120_01' +branch_labels = None +depends_on = None + + +def _qualified_column_reference(schema: str | None, table: str, column: str) -> str: + if schema: + return f'{schema}.{table}.{column}' + return f'{table}.{column}' + + +def upgrade() -> None: + schema = context.get_context().version_table_schema + + op.create_table( + 'generation_reply', + sa.Column('run_id', postgresql.UUID(as_uuid=True), nullable=False), + sa.Column('path', sa.Text(), nullable=False), + sa.Column('value', postgresql.JSONB(astext_type=sa.Text()), nullable=False), + sa.Column('display_text', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('run_id', 'path', name='pk_generation_reply'), + sa.ForeignKeyConstraint( + ['run_id'], + [_qualified_column_reference(schema, 'generation', 'run_id')], + name='fk_generation_reply_run_id', + ondelete='CASCADE', + ), + schema=schema, + ) diff --git a/service/src/ai_document_plugin_service/service/pipeline_service.py b/service/src/ai_document_plugin_service/service/pipeline_service.py index 04b14f9..7810022 100644 --- a/service/src/ai_document_plugin_service/service/pipeline_service.py +++ b/service/src/ai_document_plugin_service/service/pipeline_service.py @@ -12,6 +12,7 @@ from ai_document_plugin_service.ai.common.trace_context import get_trace_uuid from ai_document_plugin_service.ai.knowledgemodel.dsw_client import DSWClient from ai_document_plugin_service.ai.knowledgemodel.project_version import resolve_named_version +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_diff import ChangeNode, change_tree from ai_document_plugin_service.ai.persistence.assignment_saver_component import DBSaver from ai_document_plugin_service.ai.persistence.database import ( Database, @@ -30,14 +31,13 @@ PipelineStatus, PipelineStatusResponse, PipelineSummaryResponse, + QuestionnaireChangeNodeResponse, + QuestionnaireChangesResponse, + QuestionnaireValueChangeResponse, TemplateDetail, ) from ai_document_plugin_service.service.errors import ConflictError, NotConfiguredError, NotFoundError from ai_document_plugin_service.service.pipeline_queue_manager import PipelineQueueManager -from ai_document_plugin_service.service.questionnaire_state_service import ( - QuestionnaireState, - QuestionnaireStateService, -) logger = logging.getLogger(__name__) @@ -100,14 +100,14 @@ def _generation_record_to_summary_response(record: GenerationRecord) -> Pipeline ) -def _succeeded_update(output: PipelineOutput, questionnaire_state: QuestionnaireState) -> GenerationUpdate: +def _succeeded_update(output: PipelineOutput, source_event_uuid: UUID) -> GenerationUpdate: """The generation fields a finished run writes.""" return { 'status': PipelineStatus.SUCCEEDED, 'knowledge_model_uuid': output.knowledge_model_uuid, 'result_markdown': output.markdown, 'progress_message': None, - 'source_event_uuid': questionnaire_state.event_uuid, + 'source_event_uuid': source_event_uuid, } @@ -165,18 +165,53 @@ def _log_background_update_failure(task: Task[object]) -> None: logger.error('Failed to persist pipeline progress message', exc_info=error) +def _change_node_response(node: ChangeNode) -> QuestionnaireChangeNodeResponse: + change = node.change + return QuestionnaireChangeNodeResponse( + path=node.path, + kind=node.kind.value, + title=node.title, + change=QuestionnaireValueChangeResponse( + kind=change.kind.value, + old_value=change.old_value, + new_value=change.new_value, + ) + if change is not None + else None, + answer=node.answer, + children=[_change_node_response(child) for child in node.children], + ) + + class PipelineService: def __init__( self, pipeline_queue_manager: PipelineQueueManager, database: Database, - questionnaire_state_service: QuestionnaireStateService, ) -> None: self.pipeline_queue_manager = pipeline_queue_manager self.database = database - self.questionnaire_state_service = questionnaire_state_service self._llm_clients = LlmClientTenantStore() + async def get_questionnaire_changes(self, run_id: UUID, auth: AuthenticatedUser) -> QuestionnaireChangesResponse: + """What changed in the questionnaire's answers since the run was generated. + + Not available for runs that did not store their replies; those have no event baseline either. + + Raises: + NotFoundError: If the run does not exist or belongs to another user. + """ + record = await self.database.get_generation(run_id, auth.tenant_uuid, auth.user_uuid) + if record is None: + raise NotFoundError(NotFoundError.PIPELINE_RUN_MESSAGE) + if record.status != PipelineStatus.SUCCEEDED or record.source_event_uuid is None: + return QuestionnaireChangesResponse(available=False, tree=[]) + + stored = await self.database.get_generation_replies(run_id) + current_detail = await DSWClient(auth.token, auth.api_url).get_questionnaire_detail(record.questionnaire_uuid) + tree = change_tree(stored, current_detail) + return QuestionnaireChangesResponse(available=True, tree=[_change_node_response(node) for node in tree]) + async def get_pipeline_status(self, run_id: UUID, auth: AuthenticatedUser) -> PipelineStatusResponse | None: record = await self.database.get_generation(run_id, auth.tenant_uuid, auth.user_uuid) if record is None: @@ -480,7 +515,7 @@ def on_progress(message: str) -> None: dsw_client = DSWClient(auth.token, auth.api_url) # Taken right before run_pipeline reads the answers, so an edit in between only makes the run look # changed, never unchanged. A failure here fails the run: it would otherwise lose the change check. - questionnaire_state = await self.questionnaire_state_service.capture(dsw_client, questionnaire_uuid) + source_event_uuid = await dsw_client.get_latest_event_uuid(questionnaire_uuid) output = await run_pipeline( questionnaire_uuid=questionnaire_uuid, template_uuid=template_uuid, @@ -504,12 +539,13 @@ def on_progress(message: str) -> None: run_id, auth.tenant_uuid, expected_statuses=(PipelineStatus.RUNNING,), - **_succeeded_update(output, questionnaire_state), + **_succeeded_update(output, source_event_uuid), ) if record is None: # Cancellation won the atomic status transition. Discard the output # and skip success stats instead of reviving the cancelled run. return + await self.database.save_generation_replies(run_id, output.reply_snapshot) await self.database.create_generation_stats(run_id, get_trace_uuid(), **_succeeded_stats(output)) logger.info( 'Pipeline run status updated to succeeded', diff --git a/service/src/ai_document_plugin_service/service/questionnaire_state_service.py b/service/src/ai_document_plugin_service/service/questionnaire_state_service.py deleted file mode 100644 index d078a8b..0000000 --- a/service/src/ai_document_plugin_service/service/questionnaire_state_service.py +++ /dev/null @@ -1,18 +0,0 @@ -"""The state of a questionnaire at the time a document was generated.""" - -from dataclasses import dataclass -from uuid import UUID - -from ai_document_plugin_service.ai.knowledgemodel.dsw_client import DSWClient - - -@dataclass(frozen=True) -class QuestionnaireState: - event_uuid: UUID - - -class QuestionnaireStateService: - @staticmethod - async def capture(dsw_client: DSWClient, questionnaire_uuid: UUID) -> QuestionnaireState: - """Read the current state id of the questionnaire.""" - return QuestionnaireState(event_uuid=await dsw_client.get_latest_event_uuid(questionnaire_uuid)) diff --git a/service/tests/generation/test_dmp_generator.py b/service/tests/generation/test_dmp_generator.py index 1383c7d..64d9471 100644 --- a/service/tests/generation/test_dmp_generator.py +++ b/service/tests/generation/test_dmp_generator.py @@ -12,7 +12,6 @@ ) from ai_document_plugin_service.ai.generation.llm import GenerationLLM from ai_document_plugin_service.ai.generation.parse_answers import parse_answer -from ai_document_plugin_service.ai.knowledgemodel.parser_component import ParserComponent from ai_document_plugin_service.cover_page.cover_page_definition import ( cover_page_assignment_field_labels, ) @@ -44,6 +43,7 @@ def _serialize_assignments(assignments: list[SectionAssignment]) -> list[Seriali def _km_fixture() -> dict: return { + 'chapterUuids': ['ch'], 'entities': { 'phases': {}, 'questions': { @@ -55,52 +55,7 @@ def _km_fixture() -> dict: 'yes': {'label': 'Yes', 'advice': None}, 'no': {'label': 'No', 'advice': None}, }, - 'chapters': {}, - 'choices': {}, - }, - } - - -def _reachable_km_fixture() -> dict: - return { - 'chapterUuids': ['chapter'], - 'entities': { - 'chapters': { - 'chapter': { - 'uuid': 'chapter', - 'title': 'Chapter', - 'questionUuids': ['rootQ', 'datasetsQ'], - }, - }, - 'phases': {}, - 'questions': { - 'rootQ': { - 'questionType': 'OptionsQuestion', - 'title': 'Root', - 'text': 'Root text', - 'answerUuids': ['yes', 'no'], - }, - 'childQ': { - 'questionType': 'ValueQuestion', - 'title': 'Child', - 'text': 'Child text', - }, - 'datasetsQ': { - 'questionType': 'ListQuestion', - 'title': 'Datasets', - 'text': 'Datasets text', - 'itemTemplateQuestionUuids': ['datasetNameQ'], - }, - 'datasetNameQ': { - 'questionType': 'ValueQuestion', - 'title': 'Dataset name', - 'text': 'Dataset name text', - }, - }, - 'answers': { - 'yes': {'label': 'Yes', 'advice': None, 'followUpUuids': ['childQ']}, - 'no': {'label': 'No', 'advice': None, 'followUpUuids': []}, - }, + 'chapters': {'ch': {'title': 'Chapter', 'questionUuids': ['itemQ', 'neighborQ']}}, 'choices': {}, }, } @@ -119,6 +74,7 @@ def _questionnaire_detail_fixture() -> dict: def _km_with_phase_fixture() -> dict: return { + 'chapterUuids': [], 'entities': { 'phases': { 'phase-1': { @@ -350,68 +306,6 @@ def test_handle_single_reply_adds_synthetic_neighbour_answers_from_depth_two() - assert synthetic['debug-info'] -def test_filter_reachable_replies_drops_stale_option_branch() -> None: - component = _component() - km = _reachable_km_fixture() - replies = { - 'chapter.rootQ': {'value': {'type': 'AnswerReply', 'value': 'no'}}, - 'chapter.rootQ.yes.childQ': { - 'value': { - 'type': 'StringReply', - 'value': 'stale child', - }, - }, - } - - filtered = component._filter_reachable_replies(replies, km) - - assert filtered == { - 'chapter.rootQ': {'value': {'type': 'AnswerReply', 'value': 'no'}}, - } - - -def test_filter_reachable_replies_drops_removed_list_item_branch() -> None: - component = _component() - km = _reachable_km_fixture() - replies = { - 'chapter.datasetsQ': { - 'value': { - 'type': 'ItemListReply', - 'value': ['active-item'], - }, - }, - 'chapter.datasetsQ.active-item.datasetNameQ': { - 'value': { - 'type': 'StringReply', - 'value': 'active', - }, - }, - 'chapter.datasetsQ.removed-item.datasetNameQ': { - 'value': { - 'type': 'StringReply', - 'value': 'stale', - }, - }, - } - - filtered = component._filter_reachable_replies(replies, km) - - assert filtered == { - 'chapter.datasetsQ': { - 'value': { - 'type': 'ItemListReply', - 'value': ['active-item'], - }, - }, - 'chapter.datasetsQ.active-item.datasetNameQ': { - 'value': { - 'type': 'StringReply', - 'value': 'active', - }, - }, - } - - def test_match_replies_selection_returns_empty_for_no_questions() -> None: result, has_answer = _component().match_replies_selection({}, {}, _km_fixture()) assert result == [] @@ -479,6 +373,33 @@ def test_parse_answer_item_select_reply_returns_selected_item_value() -> None: assert parsed == 'English' +def test_parse_answer_item_select_reply_finds_a_list_outside_its_own_parent() -> None: + km = { + 'entities': { + 'questions': { + 'listQ': {'questionType': 'ListQuestion'}, + 'nameQ': {'questionType': 'ValueQuestion'}, + 'selectQ': {'questionType': 'ItemSelectQuestion', 'listQuestionUuid': 'listQ'}, + }, + 'answers': {}, + }, + } + replies = { + 'chapterA.listQ': {'value': {'type': 'ItemListReply', 'value': ['selected-item']}}, + 'chapterA.listQ.selected-item.nameQ': {'value': {'type': 'StringReply', 'value': 'Alice'}}, + 'chapterB.parentQ.answer.selectQ': {'value': {'type': 'ItemSelectReply', 'value': 'selected-item'}}, + } + + parsed = parse_answer( + replies['chapterB.parentQ.answer.selectQ']['value'], + km, + replies=replies, + question_path='chapterB.parentQ.answer.selectQ', + ) + + assert parsed == 'Alice' + + def test_parse_answer_integration_reply_returns_first_raw_and_url() -> None: km = { 'entities': { @@ -553,45 +474,6 @@ def test_parse_answer_integration_reply_handles_none_values_in_raw_mapping() -> assert parsed == ('{"name": "Zenodo", "homepage": null, "url": null, "doi": null, "description": null} value') -def test_parser_component_item_select_reply_uses_integration_raw_url() -> None: - parser = ParserComponent() - parser.km = { - 'entities': { - 'questions': { - 'integrationQ': {'questionType': 'IntegrationQuestion'}, - }, - }, - } - replies = { - 'chapter.selectQ': { - 'value': { - 'type': 'ItemSelectReply', - 'value': 'selected-item', - }, - }, - 'chapter.listQ.selected-item.reply.integrationQ': { - 'value': { - 'type': 'IntegrationReply', - 'value': { - 'type': 'IntegrationType', - 'value': 'value', - 'raw': { - 'homepage': 'https://tools.ietf.org/html/rfc4180', - 'doi': '10.25504/FAIRsharing.1943d4', - }, - }, - }, - }, - } - - parsed = parser.get_item_select_question_reply( - replies, - path='chapter.selectQ', - ) - - assert parsed == ('{"homepage": "https://tools.ietf.org/html/rfc4180", "doi": "10.25504/FAIRsharing.1943d4"} value') - - async def test_run_renders_parent_and_leaf_sections() -> None: stub = StubGenerationLLM() component = _component(stub) @@ -606,7 +488,7 @@ async def test_run_renders_parent_and_leaf_sections() -> None: title='Leaf', assignments={ 'itemQ': { - 'question_path': 'ch.listQ.itemQ', + 'question_path': 'ch.itemQ', 'question_title': 'Item', 'question_text': 'Item text', 'children': {}, @@ -617,7 +499,7 @@ async def test_run_renders_parent_and_leaf_sections() -> None: ), ] replies = { - 'ch.listQ.itemQ': {'value': {'type': 'AnswerReply', 'value': 'yes'}}, + 'ch.itemQ': {'value': {'type': 'AnswerReply', 'value': 'yes'}}, } result = await component.run_async( diff --git a/service/tests/knowledgemodel/test_list_items.py b/service/tests/knowledgemodel/test_list_items.py new file mode 100644 index 0000000..640152d --- /dev/null +++ b/service/tests/knowledgemodel/test_list_items.py @@ -0,0 +1,30 @@ +from ai_document_plugin_service.ai.knowledgemodel.list_items import find_list_path + + +def items(*uuids: str) -> dict[str, object]: + return {'type': 'ItemListReply', 'value': list(uuids)} + + +def test_finds_a_list_anywhere_in_the_questionnaire() -> None: + replies = [('c1.other.a1.list', items('i1')), ('c2.deep.pick', {'type': 'ItemSelectReply', 'value': 'i1'})] + + assert find_list_path('list', 'i1', replies) == 'c1.other.a1.list' + + +def test_picks_the_reply_that_holds_the_item_when_the_list_is_repeated() -> None: + replies = [('c1.outer.o1.list', items('i1')), ('c1.outer.o2.list', items('i2'))] + + assert find_list_path('list', 'i2', replies) == 'c1.outer.o2.list' + + +def test_ignores_other_lists_and_non_list_replies() -> None: + replies = [ + ('c1.mylist', items('i1')), + ('c1.list', {'type': 'StringReply', 'value': 'i1'}), + ] + + assert find_list_path('list', 'i1', replies) is None + + +def test_returns_none_for_an_item_no_list_holds() -> None: + assert find_list_path('list', 'gone', [('c1.list', items('i1'))]) is None diff --git a/service/tests/knowledgemodel/test_questionnaire_diff.py b/service/tests/knowledgemodel/test_questionnaire_diff.py new file mode 100644 index 0000000..affb517 --- /dev/null +++ b/service/tests/knowledgemodel/test_questionnaire_diff.py @@ -0,0 +1,310 @@ +import contextlib +import copy +from collections.abc import Iterable +from typing import Any +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_diff import ( + NO_LONGER_IN_QUESTIONNAIRE, + ChangeKind, + ChangeNode, + NodeKind, + ValueChange, + change_tree, + diff_replies, +) +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot + + +def u(number: int) -> str: + return str(UUID(int=number)) + + +YES, NO = u(1), u(2) +ITEM_1, ITEM_2 = u(5), u(6) + +KM: dict[str, Any] = { + 'chapterUuids': ['c1'], + 'entities': { + 'chapters': {'c1': {'title': 'Data', 'questionUuids': ['opt', 'items', 'pick', 'plain']}}, + 'questions': { + 'opt': {'questionType': 'OptionsQuestion', 'title': 'Reuse?'}, + 'why': {'questionType': 'ValueQuestion', 'title': 'Why?'}, + 'items': { + 'questionType': 'ListQuestion', + 'title': 'Datasets', + 'itemTemplateQuestionUuids': ['name', 'fmt'], + }, + 'name': {'questionType': 'ValueQuestion', 'title': 'Name'}, + 'fmt': {'questionType': 'ValueQuestion', 'title': 'Format'}, + 'pick': {'questionType': 'ItemSelectQuestion', 'title': 'Main dataset', 'listQuestionUuid': 'items'}, + 'plain': {'questionType': 'ValueQuestion', 'title': 'Notes'}, + }, + 'answers': {YES: {'label': 'Yes', 'followUpUuids': ['why']}, NO: {'label': 'No', 'followUpUuids': []}}, + 'choices': {}, + }, +} + + +def reply(reply_type: str, value: Any) -> dict[str, Any]: + return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': None} + + +def text(path: str, value: str) -> StoredReply: + return StoredReply(path, {'type': 'StringReply', 'value': value}) + + +def tree( + old_replies: dict[str, Any], + new_replies: dict[str, Any], + km: dict[str, Any] | None = None, +) -> list[ChangeNode]: + stored = build_snapshot(KM, old_replies) + return change_tree(stored, {'knowledgeModel': km or KM, 'replies': new_replies}) + + +def outline(nodes: Iterable[ChangeNode], depth: int = 0) -> list[tuple[int, str | None, ChangeKind | None]]: + """The tree as (depth, title, kind of change) lines, in order.""" + lines: list[tuple[int, str | None, ChangeKind | None]] = [] + for node in nodes: + lines.append((depth, node.title, node.change.kind if node.change else None)) + lines.extend(outline(node.children, depth + 1)) + return lines + + +def find(nodes: Iterable[ChangeNode], path: str) -> ChangeNode: + for node in nodes: + if node.path == path: + return node + with contextlib.suppress(LookupError): + return find(node.children, path) + raise LookupError(path) + + +def test_diff_reports_added_changed_and_removed_replies_ordered_by_path() -> None: + old = [text('a', 'same'), text('b', 'before'), text('c', 'gone')] + new = [text('a', 'same'), text('b', 'after'), text('d', 'new')] + + changes = diff_replies(old, new) + + assert [(change.path, change.kind) for change in changes] == [ + ('b', ChangeKind.CHANGED), + ('c', ChangeKind.REMOVED), + ('d', ChangeKind.ADDED), + ] + + +def test_diff_of_identical_snapshots_is_empty() -> None: + assert diff_replies([text('a', 'same')], [text('a', 'same')]) == [] + + +def test_diff_ignores_the_stored_label_since_it_is_not_part_of_the_value() -> None: + old = StoredReply('a', {'type': 'AnswerReply', 'value': YES}, display_text='Yes') + new = StoredReply('a', {'type': 'AnswerReply', 'value': YES}, display_text='Ano') + + assert diff_replies([old], [new]) == [] + + +def test_diff_sees_a_reordered_item_list_as_a_change() -> None: + old = StoredReply('l', {'type': 'ItemListReply', 'value': [ITEM_1, ITEM_2]}) + new = StoredReply('l', {'type': 'ItemListReply', 'value': [ITEM_2, ITEM_1]}) + + assert [change.kind for change in diff_replies([old], [new])] == [ChangeKind.CHANGED] + + +def test_diff_sees_a_changed_integration_record_with_the_same_text_as_a_change() -> None: + def zenodo(record_id: int) -> StoredReply: + value = {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': record_id}} + return StoredReply('i', {'type': 'IntegrationReply', 'value': value}) + + old, new = zenodo(1), zenodo(2) + + assert [change.kind for change in diff_replies([old], [new])] == [ChangeKind.CHANGED] + + +def test_a_changed_text_sits_under_its_chapter_with_both_values() -> None: + old = {'c1.plain': reply('StringReply', 'before')} + new = {'c1.plain': reply('StringReply', 'after')} + + assert tree(old, new) == [ + ChangeNode( + 'c1', + NodeKind.CHAPTER, + 'Data', + children=( + ChangeNode( + 'c1.plain', + NodeKind.QUESTION, + 'Notes', + change=ValueChange(ChangeKind.CHANGED, 'before', 'after'), + ), + ), + ), + ] + + +def test_describes_integration_replies_by_their_text() -> None: + old = {'c1.plain': reply('IntegrationReply', {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': 1}})} + new = {'c1.plain': reply('IntegrationReply', {'type': 'PlainType', 'value': 'Dryad'})} + + change = find(tree(old, new), 'c1.plain').change + + assert change == ValueChange(ChangeKind.CHANGED, 'Zenodo', 'Dryad') + + +def test_describes_answers_by_their_labels() -> None: + change = find(tree({'c1.opt': reply('AnswerReply', YES)}, {'c1.opt': reply('AnswerReply', NO)}), 'c1.opt').change + + assert change == ValueChange(ChangeKind.CHANGED, 'Yes', 'No') + + +def test_a_removed_answer_has_no_new_value() -> None: + change = find(tree({'c1.plain': reply('StringReply', 'before')}, {}), 'c1.plain').change + + assert change == ValueChange(ChangeKind.REMOVED, 'before', None) + + +def test_an_answer_the_knowledge_model_no_longer_has_falls_back_to_the_stored_label() -> None: + km_without_yes = copy.deepcopy(KM) + del km_without_yes['entities']['answers'][YES] + + nodes = tree({'c1.opt': reply('AnswerReply', YES)}, {'c1.opt': reply('AnswerReply', NO)}, km_without_yes) + + assert find(nodes, 'c1.opt').change == ValueChange(ChangeKind.CHANGED, 'Yes', 'No') + + +def test_follows_the_order_of_the_questionnaire_not_of_the_paths() -> None: + km = copy.deepcopy(KM) + km['entities']['chapters']['c1']['questionUuids'] = ['plain', 'opt', 'items', 'pick'] + old = {'c1.opt': reply('AnswerReply', NO), 'c1.plain': reply('StringReply', 'before')} + new = {'c1.opt': reply('AnswerReply', YES), 'c1.plain': reply('StringReply', 'after')} + + assert [title for _, title, _ in outline(tree(old, new, km))] == ['Data', 'Notes', 'Reuse?'] + + +def test_a_question_inside_a_list_item_sits_under_the_list_and_the_item() -> None: + old = {'c1.items': reply('ItemListReply', [ITEM_1]), f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey')} + new = {**old, f'c1.items.{ITEM_1}.fmt': reply('StringReply', 'csv')} + + assert outline(tree(old, new)) == [ + (0, 'Data', None), + (1, 'Datasets', None), + (2, 'Survey', None), + (3, 'Format', ChangeKind.ADDED), + ] + assert find(tree(old, new), f'c1.items.{ITEM_1}').kind == NodeKind.ITEM + + +def test_a_changed_follow_up_shows_the_answer_of_its_unchanged_question() -> None: + old = {'c1.opt': reply('AnswerReply', YES)} + new = {**old, f'c1.opt.{YES}.why': reply('StringReply', 'Public data')} + + question = find(tree(old, new), 'c1.opt') + + assert (question.change, question.answer) == (None, 'Yes') + assert [child.path for child in question.children] == [f'c1.opt.{YES}.why'] + + +def test_a_changed_answer_is_shown_once_with_the_follow_ups_of_the_old_answer_under_it() -> None: + old = {'c1.opt': reply('AnswerReply', YES), f'c1.opt.{YES}.why': reply('StringReply', 'Public data')} + new = {'c1.opt': reply('AnswerReply', NO)} + + assert outline(tree(old, new)) == [ + (0, 'Data', None), + (1, 'Reuse?', ChangeKind.CHANGED), + (2, 'Why?', ChangeKind.REMOVED), + ] + assert find(tree(old, new), 'c1.opt').answer is None + + +def test_an_added_item_is_shown_under_the_changed_list() -> None: + old = {'c1.items': reply('ItemListReply', [ITEM_1]), f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey')} + new = { + 'c1.items': reply('ItemListReply', [ITEM_1, ITEM_2]), + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey'), + f'c1.items.{ITEM_2}.name': reply('StringReply', 'Interviews'), + } + + nodes = tree(old, new) + + assert find(nodes, 'c1.items').change == ValueChange(ChangeKind.CHANGED, 'Survey', 'Survey, Interviews') + assert outline(nodes)[2:] == [(2, 'Interviews', None), (3, 'Name', ChangeKind.ADDED)] + + +def test_a_deleted_item_keeps_its_place_and_its_old_title() -> None: + old = { + 'c1.items': reply('ItemListReply', [ITEM_1, ITEM_2]), + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey'), + f'c1.items.{ITEM_2}.name': reply('StringReply', 'Interviews'), + } + new = { + 'c1.items': reply('ItemListReply', [ITEM_1]), + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey 2025'), + } + + assert outline(tree(old, new))[1:] == [ + (1, 'Datasets', ChangeKind.CHANGED), + (2, 'Survey 2025', None), + (3, 'Name', ChangeKind.CHANGED), + (2, 'Interviews', None), + (3, 'Name', ChangeKind.REMOVED), + ] + + +def test_an_item_without_a_title_answer_is_called_untitled() -> None: + nodes = tree({}, {'c1.items': reply('ItemListReply', [ITEM_1])}) + + assert find(nodes, 'c1.items').change == ValueChange(ChangeKind.ADDED, None, 'Untitled item') + + +def test_an_item_select_is_described_by_the_title_of_the_selected_item() -> None: + items = {'c1.items': reply('ItemListReply', [ITEM_1, ITEM_2])} + titles = { + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey'), + f'c1.items.{ITEM_2}.name': reply('StringReply', 'Interviews'), + } + old = {**items, **titles, 'c1.pick': reply('ItemSelectReply', ITEM_1)} + new = {**items, **titles, 'c1.pick': reply('ItemSelectReply', ITEM_2)} + + assert find(tree(old, new), 'c1.pick').change == ValueChange(ChangeKind.CHANGED, 'Survey', 'Interviews') + + +def test_an_item_select_finds_its_list_outside_its_own_parent() -> None: + km = copy.deepcopy(KM) + km['chapterUuids'] = ['c1', 'c2'] + km['entities']['chapters']['c1']['questionUuids'].remove('pick') + km['entities']['chapters']['c2'] = {'title': 'Use', 'questionUuids': ['pick']} + items = {'c1.items': reply('ItemListReply', [ITEM_1, ITEM_2])} + titles = { + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey'), + f'c1.items.{ITEM_2}.name': reply('StringReply', 'Interviews'), + } + old = {**items, **titles, 'c2.pick': reply('ItemSelectReply', ITEM_1)} + new = {**items, **titles, 'c2.pick': reply('ItemSelectReply', ITEM_2)} + + stored = build_snapshot(km, old) + nodes = change_tree(stored, {'knowledgeModel': km, 'replies': new}) + + assert find(nodes, 'c2.pick').change == ValueChange(ChangeKind.CHANGED, 'Survey', 'Interviews') + + +def test_a_reply_to_a_question_the_knowledge_model_no_longer_has_goes_into_a_last_group() -> None: + km_without_notes = copy.deepcopy(KM) + del km_without_notes['entities']['questions']['plain'] + km_without_notes['entities']['chapters']['c1']['questionUuids'].remove('plain') + old = {'c1.opt': reply('AnswerReply', YES), 'c1.plain': reply('StringReply', 'gone')} + new = {'c1.opt': reply('AnswerReply', NO)} + + nodes = tree(old, new, km_without_notes) + + assert [(node.path, node.title) for node in nodes] == [('c1', 'Data'), ('', NO_LONGER_IN_QUESTIONNAIRE)] + assert nodes[-1].children == ( + ChangeNode('c1.plain', NodeKind.QUESTION, None, change=ValueChange(ChangeKind.REMOVED, 'gone', None)), + ) + + +def test_nothing_is_reported_when_only_unreachable_replies_differ() -> None: + old = {'c1.opt': reply('AnswerReply', NO)} + new = {'c1.opt': reply('AnswerReply', NO), f'c1.opt.{YES}.why': reply('StringReply', 'left over')} + + assert tree(old, new) == [] diff --git a/service/tests/knowledgemodel/test_questionnaire_snapshot.py b/service/tests/knowledgemodel/test_questionnaire_snapshot.py new file mode 100644 index 0000000..f733f1a --- /dev/null +++ b/service/tests/knowledgemodel/test_questionnaire_snapshot.py @@ -0,0 +1,117 @@ +from typing import Any +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot + + +def u(number: int) -> str: + return str(UUID(int=number)) + + +YES, NO = u(1), u(2) +CSV, JSON = u(3), u(4) +ITEM_1, ITEM_2 = u(5), u(6) + +KM = { + 'chapterUuids': ['c1'], + 'entities': { + 'chapters': {'c1': {'title': 'Data', 'questionUuids': ['opt', 'multi', 'items', 'plain', 'integ', 'file']}}, + 'questions': { + 'opt': {'questionType': 'OptionsQuestion', 'title': 'Reuse?'}, + 'why': {'questionType': 'ValueQuestion', 'title': 'Why'}, + 'multi': {'questionType': 'MultiChoiceQuestion', 'title': 'Formats'}, + 'items': {'questionType': 'ListQuestion', 'title': 'Datasets', 'itemTemplateQuestionUuids': ['name']}, + 'name': {'questionType': 'ValueQuestion', 'title': 'Name'}, + 'plain': {'questionType': 'ValueQuestion', 'title': 'Notes'}, + 'integ': {'questionType': 'IntegrationQuestion', 'title': 'Repository'}, + 'file': {'questionType': 'FileQuestion', 'title': 'Attachment'}, + }, + 'answers': { + YES: {'label': 'Yes', 'followUpUuids': ['why']}, + NO: {'label': 'No', 'followUpUuids': []}, + }, + 'choices': {CSV: {'label': 'CSV'}, JSON: {'label': 'JSON'}}, + }, +} + + +def reply(reply_type: str, value: Any) -> dict[str, Any]: + return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': None} + + +def test_stores_the_value_as_dsw_sends_it_without_who_made_it_and_when() -> None: + snapshot = build_snapshot(KM, {'c1.plain': reply('StringReply', 'Some notes')}) + + assert snapshot == [StoredReply('c1.plain', {'type': 'StringReply', 'value': 'Some notes'})] + + +def test_stores_integration_replies_with_the_raw_payload() -> None: + value = {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': 1}} + + assert build_snapshot(KM, {'c1.integ': reply('IntegrationReply', value)}) == [ + StoredReply('c1.integ', {'type': 'IntegrationReply', 'value': value}), + ] + + +def test_stores_the_selected_answer_with_its_label() -> None: + assert build_snapshot(KM, {'c1.opt': reply('AnswerReply', YES)}) == [ + StoredReply('c1.opt', {'type': 'AnswerReply', 'value': YES}, display_text='Yes'), + ] + + +def test_stores_selected_choices_with_their_labels() -> None: + assert build_snapshot(KM, {'c1.multi': reply('MultiChoiceReply', [JSON, CSV])}) == [ + StoredReply('c1.multi', {'type': 'MultiChoiceReply', 'value': [JSON, CSV]}, display_text='JSON, CSV'), + ] + + +def test_stores_list_items_in_order() -> None: + snapshot = build_snapshot(KM, {'c1.items': reply('ItemListReply', [ITEM_2, ITEM_1])}) + + assert snapshot == [StoredReply('c1.items', {'type': 'ItemListReply', 'value': [ITEM_2, ITEM_1]})] + + +def test_stores_replies_of_types_it_does_not_know() -> None: + snapshot = build_snapshot(KM, {'c1.plain': reply('FutureReply', {'anything': 1})}) + + assert snapshot == [StoredReply('c1.plain', {'type': 'FutureReply', 'value': {'anything': 1}})] + + +def test_leaves_out_empty_replies() -> None: + replies = { + 'c1.plain': reply('StringReply', ' '), + 'c1.multi': reply('MultiChoiceReply', []), + 'c1.items': reply('ItemListReply', []), + 'c1.integ': reply('IntegrationReply', {'type': 'PlainType', 'value': ''}), + } + + assert build_snapshot(KM, replies) == [] + + +def test_leaves_out_file_replies() -> None: + assert build_snapshot(KM, {'c1.file': reply('FileReply', u(9))}) == [] + + +def test_leaves_out_unreachable_replies() -> None: + replies = { + 'c1.opt': reply('AnswerReply', NO), + f'c1.opt.{YES}.why': reply('StringReply', 'left over from an earlier answer'), + f'c1.items.{ITEM_1}.name': reply('StringReply', 'item of a list without items'), + } + + assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.opt'] + + +def test_skips_a_reply_without_a_type_and_keeps_the_others() -> None: + replies = { + 'c1.multi': {'value': {'value': [CSV]}}, + 'c1.plain': reply('StringReply', 'kept'), + } + + assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.plain'] + + +def test_orders_the_snapshot_by_path() -> None: + replies = {'c1.plain': reply('StringReply', 'b'), 'c1.opt': reply('AnswerReply', NO)} + + assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.opt', 'c1.plain'] diff --git a/service/tests/knowledgemodel/test_reachable_replies.py b/service/tests/knowledgemodel/test_reachable_replies.py new file mode 100644 index 0000000..bfd98e9 --- /dev/null +++ b/service/tests/knowledgemodel/test_reachable_replies.py @@ -0,0 +1,124 @@ +from typing import Any + +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies + +# Chapter c1 holds three questions. The options question opt has answers a1 and a2, which lead to the value +# questions f1 and f2. The list question items has the value question t1 and the list question nested, with the +# value question n1, in its item template. The value question plain has no children. +KM = { + 'chapterUuids': ['c1'], + 'entities': { + 'chapters': {'c1': {'questionUuids': ['opt', 'items', 'plain']}}, + 'questions': { + 'opt': {'questionType': 'OptionsQuestion', 'answerUuids': ['a1', 'a2']}, + 'f1': {'questionType': 'ValueQuestion'}, + 'f2': {'questionType': 'ValueQuestion'}, + 'items': {'questionType': 'ListQuestion', 'itemTemplateQuestionUuids': ['t1', 'nested']}, + 't1': {'questionType': 'ValueQuestion'}, + 'nested': {'questionType': 'ListQuestion', 'itemTemplateQuestionUuids': ['n1']}, + 'n1': {'questionType': 'ValueQuestion'}, + 'plain': {'questionType': 'ValueQuestion'}, + }, + 'answers': { + 'a1': {'followUpUuids': ['f1']}, + 'a2': {'followUpUuids': ['f2']}, + }, + }, +} + + +def _reply(reply_type: str, value: Any) -> dict[str, Any]: + return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': None} + + +def _text(value: str) -> dict[str, Any]: + return _reply('StringReply', value) + + +def test_keeps_a_reply_of_a_chapter_question() -> None: + replies = {'c1.plain': _text('kept')} + + assert reachable_replies(KM, replies) == replies + + +def test_keeps_the_order_of_the_replies() -> None: + replies = { + 'c1.items.i2.t1': _text('second item'), + 'c1.plain': _text('plain'), + 'c1.items': _reply('ItemListReply', ['i1', 'i2']), + 'c1.items.i1.t1': _text('first item'), + } + + assert list(reachable_replies(KM, replies)) == list(replies) + + +def test_keeps_the_reply_object_untouched() -> None: + replies = {'c1.plain': _text('kept')} + + assert reachable_replies(KM, replies)['c1.plain'] is replies['c1.plain'] + + +def test_keeps_follow_ups_of_the_selected_answer_only() -> None: + replies = { + 'c1.opt': _reply('AnswerReply', 'a1'), + 'c1.opt.a1.f1': _text('applies'), + 'c1.opt.a2.f2': _text('left over from an earlier answer'), + } + + assert set(reachable_replies(KM, replies)) == {'c1.opt', 'c1.opt.a1.f1'} + + +def test_follow_ups_of_an_unanswered_options_question_are_unreachable() -> None: + replies = {'c1.opt.a1.f1': _text('left over')} + + assert reachable_replies(KM, replies) == {} + + +def test_follow_ups_are_unreachable_when_the_options_reply_has_another_type() -> None: + replies = {'c1.opt': _text('not an answer'), 'c1.opt.a1.f1': _text('left over')} + + assert set(reachable_replies(KM, replies)) == {'c1.opt'} + + +def test_keeps_replies_of_listed_items_only() -> None: + replies = { + 'c1.items': _reply('ItemListReply', ['i1']), + 'c1.items.i1.t1': _text('listed'), + 'c1.items.i2.t1': _text('deleted item'), + } + + assert set(reachable_replies(KM, replies)) == {'c1.items', 'c1.items.i1.t1'} + + +def test_a_list_without_a_reply_has_no_reachable_items() -> None: + replies = {'c1.items.i1.t1': _text('left over')} + + assert reachable_replies(KM, replies) == {} + + +def test_follows_lists_nested_in_items() -> None: + replies = { + 'c1.items': _reply('ItemListReply', ['i1', 'i2']), + 'c1.items.i1.nested': _reply('ItemListReply', ['n']), + 'c1.items.i1.nested.n.n1': _text('listed'), + 'c1.items.i1.nested.gone.n1': _text('deleted nested item'), + 'c1.items.i2.nested.n.n1': _text('item i2 has no nested list reply'), + } + + assert set(reachable_replies(KM, replies)) == { + 'c1.items', + 'c1.items.i1.nested', + 'c1.items.i1.nested.n.n1', + } + + +def test_drops_a_reply_to_a_question_that_is_not_in_the_knowledge_model() -> None: + replies = {'c1.removed': _text('question no longer exists'), 'c1.plain': _text('kept')} + + assert set(reachable_replies(KM, replies)) == {'c1.plain'} + + +def test_drops_a_reply_under_the_wrong_chapter() -> None: + replies = {'other.plain': _text('wrong chapter')} + + assert reachable_replies(KM, replies) == {} diff --git a/service/tests/service/test_pipeline_admission.py b/service/tests/service/test_pipeline_admission.py index 123a2ba..c716f4f 100644 --- a/service/tests/service/test_pipeline_admission.py +++ b/service/tests/service/test_pipeline_admission.py @@ -28,7 +28,7 @@ async def test_admission_uses_cancellable_states_in_owned_project_history(admiss database.list_generations.return_value = [ Mock(template_uuid=payload.template_uuid if same_template else uuid4(), status=status), ] - service = PipelineService(queue, database, Mock()) + service = PipelineService(queue, database) with patch('ai_document_plugin_service.service.pipeline_service.DSWClient') as client: client.return_value.get_project_versions = AsyncMock(return_value=[]) if same_template and status in {PipelineStatus.QUEUED, PipelineStatus.RUNNING}: @@ -51,7 +51,7 @@ async def test_admission_rejects_deleted_template(admission): with patch('ai_document_plugin_service.service.pipeline_service.DSWClient') as client: client.return_value.get_project_versions = AsyncMock(return_value=[]) with pytest.raises(NotFoundError): - await PipelineService(queue, database, Mock()).enqueue_pipeline_job(payload, Mock(), auth, Mock(), None) + await PipelineService(queue, database).enqueue_pipeline_job(payload, Mock(), auth, Mock(), None) database.create_generation.assert_not_awaited() queue.enqueue.assert_not_called() @@ -92,7 +92,7 @@ async def create_generation(**kwargs): database.get_template.side_effect = get_template database.list_generations.side_effect = list_generations database.create_generation.side_effect = create_generation - services = [PipelineService(queue, database, Mock()), PipelineService(queue, database, Mock())] + services = [PipelineService(queue, database), PipelineService(queue, database)] with patch('ai_document_plugin_service.service.pipeline_service.DSWClient') as client: client.return_value.get_project_versions = AsyncMock(return_value=[]) results = await asyncio.gather( diff --git a/service/tests/service/test_pipeline_rename.py b/service/tests/service/test_pipeline_rename.py index 07cb584..a15ef9c 100644 --- a/service/tests/service/test_pipeline_rename.py +++ b/service/tests/service/test_pipeline_rename.py @@ -42,7 +42,7 @@ async def test_rename_persists_title_for_every_run_status(auth, status): database = AsyncMock() database.get_generation.return_value = record database.update_generation.return_value = replace(record, title='New title') - service = PipelineService(Mock(), database, Mock()) + service = PipelineService(Mock(), database) result = await service.rename_pipeline(record.run_id, PipelineRenameRequest(title=' New title '), auth) @@ -56,7 +56,7 @@ async def test_rename_persists_title_for_every_run_status(auth, status): async def test_rename_does_not_update_a_run_outside_the_users_scope(auth): database = AsyncMock() database.get_generation.return_value = None - service = PipelineService(Mock(), database, Mock()) + service = PipelineService(Mock(), database) run_id = uuid4() with pytest.raises(NotFoundError): @@ -69,7 +69,7 @@ async def test_rename_does_not_update_a_run_outside_the_users_scope(auth): async def test_rename_handles_a_run_removed_before_update(auth): database = AsyncMock() database.update_generation.return_value = None - service = PipelineService(Mock(), database, Mock()) + service = PipelineService(Mock(), database) with pytest.raises(NotFoundError): await service.rename_pipeline(uuid4(), PipelineRenameRequest(title='New title'), auth)