From eabd02ca64b53d8843b1bdab2628ff73d9a1c796 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hana=20Litavsk=C3=A1?= Date: Thu, 3 Dec 2026 15:10:39 +0100 Subject: [PATCH] Fix crushing when inconsistent km --- .../ai/generation/parse_answers.py | 51 +++--- .../ai/knowledgemodel/parser_component.py | 82 ++++++---- .../knowledgemodel/test_missing_entities.py | 146 ++++++++++++++++++ 3 files changed, 230 insertions(+), 49 deletions(-) create mode 100644 service/tests/knowledgemodel/test_missing_entities.py 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 82a71ea0..32ca0223 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 @@ -7,6 +7,14 @@ RAW_URL_PATTERN = re.compile(r'https?://[^\s)]+') +def get_km_entity(km: dict, collection: str, uuid: str) -> dict[str, Any] | None: + """Resolve an entity reference, warning and skipping dangling references.""" + entity = km.get('entities', {}).get(collection, {}).get(uuid) + if entity is None: + logger.warning('Missing knowledge model entity %s in %s; skipping reference', uuid, collection) + return entity + + def _strip_markdown_images(raw_value: str) -> str: result: list[str] = [] i = 0 @@ -120,7 +128,9 @@ def _parse_item_select_reply( return '' question_uuid = question_path.rsplit('.', 1)[-1] - question = km.get('entities', {}).get('questions', {}).get(question_uuid, {}) + question = get_km_entity(km, 'questions', question_uuid) + if question is None: + return '' list_question_uuid = question.get('listQuestionUuid') if not list_question_uuid: return '' @@ -133,23 +143,36 @@ def _parse_item_select_reply( continue reply_question_uuid = reply_path.rsplit('.', 1)[-1] - question_type = km.get('entities', {}).get('questions', {}).get(reply_question_uuid, {}).get('questionType') + reply_question = get_km_entity(km, 'questions', reply_question_uuid) + if reply_question is None: + continue + + question_type = reply_question.get('questionType') reply_value = reply_payload.get('value', {}) if question_type == 'ValueQuestion': value = reply_value.get('value', '') - if value: - return value + elif question_type == 'IntegrationQuestion': + value = parse_integration_reply_value(reply_value) + else: continue - if question_type == 'IntegrationQuestion': - value = parse_integration_reply_value(reply_value) - if value: - return value + if value: + return value return '' +def _parse_multichoice_reply(answer: dict[str, Any], km: dict[str, Any]) -> str: + labels = [] + for answer_id in answer['value']: + entity = get_km_entity(km, 'choices', answer_id) + if entity is None: + continue + labels.append(entity['label']) + return ', '.join(labels) + + def parse_answer( # ruff: ignore[too-many-return-statements] answer: dict[str, Any], km: dict[str, Any], @@ -157,22 +180,14 @@ def parse_answer( # ruff: ignore[too-many-return-statements] question_path: str | None = None, ) -> str | None: answer_type = answer['type'] - entities = km['entities'] - answer_entities = entities['answers'] if answer_type == 'AnswerReply': - entity = answer_entities.get(answer['value'], None) + entity = get_km_entity(km, 'answers', answer['value']) if entity is None: - logger.debug( - 'Entity %s has no answer in the KM, strange...', - answer['value'], - ) return '' return entity['label'] + (f' ({entity["advice"]})' if entity['advice'] is not None else '') if answer_type == 'MultiChoiceReply': - return ', '.join( - [km['entities']['choices'][answer_id]['label'] for answer_id in answer['value']], - ) + return _parse_multichoice_reply(answer, km) if answer_type == 'IntegrationReply': return parse_integration_reply_value(answer) if answer_type == 'ItemListReply': 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 e445077b..bfef38d4 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 @@ -1,9 +1,8 @@ import logging -from collections.abc import Iterator from haystack import component -from ai_document_plugin_service.ai.generation.parse_answers import parse_integration_reply_value +from ai_document_plugin_service.ai.generation.parse_answers import get_km_entity, parse_integration_reply_value from ai_document_plugin_service.ai.knowledgemodel.types import ( Chapter, Choice, @@ -39,22 +38,21 @@ def run(self, data: dict) -> dict[str, list[QuestionData]]: }, ) 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) + for chapter_uuid in self.km['chapterUuids']: + parsed_chapter = self.parse_chapter(chapter_uuid, replies) + if parsed_chapter is not None: + top_level_questions.append(parsed_chapter) logger.info( 'Finished parsing knowledge model replies', extra={'chapter_count': len(top_level_questions)}, ) return {'data': top_level_questions} - 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, replies: dict) -> Chapter | None: """Parse a Chapter from the knowledge model.""" - chapter_data = self.km['entities']['chapters'][chapter_uuid] + chapter_data = get_km_entity(self.km, 'chapters', chapter_uuid) + if chapter_data is None: + return None # Create chapter first (without questions) chapter = Chapter( @@ -80,9 +78,11 @@ def parse_chapter(self, chapter_uuid: str, replies: dict) -> Chapter: chapter.questions = questions return chapter - def parse_choice(self, choice_uuid: str) -> Choice: + def parse_choice(self, choice_uuid: str) -> Choice | None: """Parse a Choice from the knowledge model.""" - choice_data = self.km['entities']['choices'][choice_uuid] + choice_data = get_km_entity(self.km, 'choices', choice_uuid) + if choice_data is None: + return None return Choice(label=choice_data['label'], uuid=choice_uuid) def parse_options_answer( @@ -91,9 +91,11 @@ def parse_options_answer( replies: dict, path: str, parent_question: OptionsQuestion | None = None, - ) -> OptionsAnswer: + ) -> OptionsAnswer | None: """Parse an OptionsAnswer from the knowledge model.""" - answer_data = self.km['entities']['answers'][answer_uuid] + answer_data = get_km_entity(self.km, 'answers', answer_uuid) + if answer_data is None: + return None # Create answer first (without followups) answer = OptionsAnswer( @@ -249,7 +251,7 @@ def parse_options_question( for answer_uuid in question.get('answerUuids', []) ] - options_question.answers = answers + options_question.answers = [answer for answer in answers if answer is not None] options_question.reply = self.get_option_reply( replies, @@ -265,7 +267,10 @@ def get_option_reply( ) -> 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', '') + if not reply: + return '' + answer = get_km_entity(self.km, 'answers', reply) + return answer.get('label', '') if answer is not None else '' def parse_multi_choice_question( self, @@ -277,12 +282,19 @@ def parse_multi_choice_question( parent_answer: OptionsAnswer | None = None, ) -> MultiChoiceQuestion: """Parse a MultiChoiceQuestion from the knowledge model.""" + choices = [] + for choice_uuid in question.get('choiceUuids', []): + choice = self.parse_choice(choice_uuid) + if choice is None: + continue + choices.append(choice) + multichoice_question = MultiChoiceQuestion( path=path, uuid=question_uuid, title=question['title'], text=question.get('text'), - choices=[self.parse_choice(choice_uuid) for choice_uuid in question.get('choiceUuids', [])], + choices=choices, parent_question=parent_question, parent_answer=parent_answer, ) @@ -300,10 +312,13 @@ def get_multichoice_reply( ) -> 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 - ] + labels = [] + for reply_value in reply_values: + choice = get_km_entity(self.km, 'choices', reply_value) + if choice is None: + continue + labels.append(choice.get('label', '')) + return labels def parse_item_select_question( self, @@ -350,19 +365,22 @@ def get_item_select_question_reply( continue question_uuid = path_parts[-1] - question_type = self.km.get('entities', {}).get('questions', {}).get(question_uuid, {}).get('questionType') + question = get_km_entity(self.km, 'questions', question_uuid) + if question is None: + continue + + question_type = question.get('questionType') if question_type == 'ValueQuestion': value = reply_payload.get('value', {}).get('value', '') - if value: - return value - continue - - if question_type == 'IntegrationQuestion': + elif question_type == 'IntegrationQuestion': answer = reply_payload.get('value', {}) value = parse_integration_reply_value(answer) - if value: - return value + else: + continue + + if value: + return value return '' @@ -388,7 +406,9 @@ def parse_question( Raises: ValueError: If the question type is unknown. """ - question = self.km['entities']['questions'][question_uuid] + question = get_km_entity(self.km, 'questions', question_uuid) + if question is None: + return None question_type = question.get('questionType') parser_by_type = { 'ValueQuestion': self.parse_value_question, diff --git a/service/tests/knowledgemodel/test_missing_entities.py b/service/tests/knowledgemodel/test_missing_entities.py new file mode 100644 index 00000000..bba2d094 --- /dev/null +++ b/service/tests/knowledgemodel/test_missing_entities.py @@ -0,0 +1,146 @@ +import logging + +import pytest + +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.ai.knowledgemodel.types import ( + Chapter, + ListQuestion, + MultiChoiceQuestion, + OptionsQuestion, +) + + +@pytest.fixture +def km(): + return { + 'chapterUuids': ['missing-chapter', 'chapter'], + 'entities': { + 'chapters': { + 'missing-chapter': {'uuid': 'missing-chapter', 'title': 'First'}, + 'chapter': {'uuid': 'chapter', 'title': 'Chapter', 'questionUuids': ['list', 'options', 'multi']}, + }, + 'questions': { + 'list': {'title': 'List', 'questionType': 'ListQuestion', 'itemTemplateQuestionUuids': ['nested']}, + 'nested': { + 'title': 'Nested list', + 'questionType': 'ListQuestion', + 'itemTemplateQuestionUuids': ['missing-question', 'value'], + }, + 'missing-question': {'title': 'Missing', 'questionType': 'ValueQuestion'}, + 'value': {'title': 'Value', 'questionType': 'ValueQuestion'}, + 'options': { + 'title': 'Options', + 'questionType': 'OptionsQuestion', + 'answerUuids': ['missing-answer', 'answer'], + }, + 'multi': { + 'title': 'Multi', + 'questionType': 'MultiChoiceQuestion', + 'choiceUuids': ['missing-choice', 'choice'], + }, + }, + 'answers': { + 'missing-answer': {'label': 'Missing', 'advice': None}, + 'answer': {'label': 'Answer', 'advice': None, 'followUpUuids': ['missing-question', 'value']}, + }, + 'choices': {'missing-choice': {'label': 'Missing'}, 'choice': {'label': 'Choice'}}, + }, + } + + +@pytest.mark.parametrize( + ('collection', 'uuid'), + [ + ('chapters', 'missing-chapter'), + ('questions', 'list'), + ('questions', 'missing-question'), + ('answers', 'missing-answer'), + ('choices', 'missing-choice'), + ], +) +def test_parser_skips_missing_entities_and_preserves_siblings(km, caplog, collection, uuid): + del km['entities'][collection][uuid] + with caplog.at_level(logging.WARNING): + chapters = ParserComponent().run({'knowledgeModel': km, 'replies': {}})['data'] + + assert any(uuid in record.message and collection in record.message for record in caplog.records) + assert all(record.levelno == logging.WARNING for record in caplog.records) + assert [chapter.uuid for chapter in chapters] == ( + ['chapter'] if collection == 'chapters' else ['missing-chapter', 'chapter'] + ) + chapter = chapters[-1] + assert isinstance(chapter, Chapter) + questions = {question.uuid: question for question in chapter.questions} + assert isinstance(questions['options'], OptionsQuestion) + assert isinstance(questions['multi'], MultiChoiceQuestion) + assert list(questions) == (['options', 'multi'] if uuid == 'list' else ['list', 'options', 'multi']) + assert [answer.uuid for answer in questions['options'].answers] == ( + ['answer'] if collection == 'answers' else ['missing-answer', 'answer'] + ) + assert [choice.uuid for choice in questions['multi'].choices] == ( + ['choice'] if collection == 'choices' else ['missing-choice', 'choice'] + ) + expected_children = ['value'] if uuid == 'missing-question' else ['missing-question', 'value'] + assert [question.uuid for question in questions['options'].answers[-1].followup_questions] == expected_children + if 'list' in questions: + assert isinstance(questions['list'], ListQuestion) + assert isinstance(questions['list'].questions[0], ListQuestion) + assert [question.uuid for question in questions['list'].questions[0].questions] == expected_children + + +@pytest.mark.parametrize('reply_type', ['AnswerReply', 'MultiChoiceReply']) +def test_missing_reply_entities_are_skipped_in_parser_and_generation(km, caplog, reply_type): + parser = ParserComponent() + parser.km = km + if reply_type == 'AnswerReply': + del km['entities']['answers']['missing-answer'] + value = 'missing-answer' + expected = '' + method = parser.get_option_reply + else: + del km['entities']['choices']['missing-choice'] + value = ['missing-choice', 'choice'] + expected = 'Choice' + method = parser.get_multichoice_reply + answer = {'type': reply_type, 'value': value} + with caplog.at_level(logging.WARNING): + parsed = method({'path': {'value': answer}}, 'path') + generated = parse_answer(answer, km) + assert parsed == (['Choice'] if reply_type == 'MultiChoiceReply' else '') + assert generated == expected + assert all('missing-' in record.message for record in caplog.records) + assert len(caplog.records) == 2 + + +def test_item_select_skips_missing_question_and_uses_next_value(km, caplog): + parser = ParserComponent() + parser.km = km + km['entities']['questions']['select'] = {'questionType': 'ItemSelectQuestion', 'listQuestionUuid': 'list'} + answer = {'type': 'ItemSelectReply', 'value': 'item'} + replies = { + 'chapter.select': {'value': answer}, + 'chapter.list.item.reply.absent': {'value': {'type': 'StringReply', 'value': 'Ignore'}}, + 'chapter.list.item.reply.value': {'value': {'type': 'StringReply', 'value': 'Keep'}}, + } + with caplog.at_level(logging.WARNING): + assert parser.get_item_select_question_reply(replies, 'chapter.select') == 'Keep' + assert parse_answer(answer, km, replies, 'chapter.select') == 'Keep' + assert len(caplog.records) == 2 + assert all('absent' in record.message for record in caplog.records) + + +def test_item_select_with_missing_own_question(km, caplog): + with caplog.at_level(logging.WARNING): + assert parse_answer({'type': 'ItemSelectReply', 'value': 'item'}, km, {}, 'chapter.absent') == '' + assert 'absent' in caplog.text + + +def test_unanswered_options_do_not_warn(km, caplog): + parser = ParserComponent() + parser.km = km + with caplog.at_level(logging.WARNING): + assert parser.get_option_reply({}, 'path') == '' + assert parser.get_multichoice_reply({}, 'path') == [] + assert not caplog.records