Skip to content

UN-2653 [FIX] Fixed issue in JSON structure parsing#1467

Merged
vishnuszipstack merged 3 commits into
mainfrom
UN-2653-bug-rc-26-the-json-structure-collapses-when-enforce-type-is-json-in-unstract-but-the-same-works-fine-when-enforce-type-is-text
Aug 2, 2025
Merged

UN-2653 [FIX] Fixed issue in JSON structure parsing#1467
vishnuszipstack merged 3 commits into
mainfrom
UN-2653-bug-rc-26-the-json-structure-collapses-when-enforce-type-is-json-in-unstract-but-the-same-works-fine-when-enforce-type-is-text

Conversation

@Deepak-Kesavan
Copy link
Copy Markdown
Contributor

@Deepak-Kesavan Deepak-Kesavan commented Aug 1, 2025

What

  • Fixed issue in JSON structure parsing

Why

  • In some scenarios JSON structure collapses with previous logic to determine and fix partial JSON.

How

  • Fixed it with more robust logic.

Can this PR break any existing features. If yes, please list possible items. If no, please explain why. (PS: Admins do not merge the PR without this section filled)

Database Migrations

Env Config

Relevant Docs

Related Issues or PRs

Dependencies Versions

Notes on Testing

Screenshots

Checklist

I have read and understood the Contribution Guidelines.

Signed-off-by: Deepak <89829542+Deepak-Kesavan@users.noreply.github.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 1, 2025

Summary by CodeRabbit

  • New Features

    • Improved handling and repair of malformed JSON strings, resulting in more reliable processing of structured data in responses.
  • Bug Fixes

    • Enhanced accuracy in parsing and interpreting complex or concatenated JSON outputs.

Walkthrough

The changes refactor JSON repair and parsing logic in the prompt service. The manual heuristic-based approach in answer_prompt.py is replaced by a new utility function, repair_json_with_best_structure, introduced in json_repair_helper.py. This function centralizes and improves the logic for repairing and parsing potentially malformed JSON strings.

Changes

Cohort / File(s) Change Summary
Answer Prompt Service Refactor
prompt-service/src/unstract/prompt_service/services/answer_prompt.py
Replaces inline JSON repair and heuristic parsing logic with a call to the new utility function repair_json_with_best_structure. Removes old imports and parsing code.
JSON Repair Utility Addition
prompt-service/src/unstract/prompt_service/utils/json_repair_helper.py
Adds the repair_json_with_best_structure function to handle intelligent JSON repair and parsing, replacing previous heuristics.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as AnswerPrompt.handle_json
    participant Helper as json_repair_helper.repair_json_with_best_structure
    participant RepairLib as json_repair.repair_json

    Caller->>Helper: Call repair_json_with_best_structure(json_str)
    Helper->>RepairLib: repair_json(json_str)
    RepairLib-->>Helper: repaired JSON (original)
    Helper->>RepairLib: repair_json("[" + json_str + "]")
    RepairLib-->>Helper: repaired JSON (wrapped array)
    Helper-->>Caller: Return best parsed structure
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch UN-2653-bug-rc-26-the-json-structure-collapses-when-enforce-type-is-json-in-unstract-but-the-same-works-fine-when-enforce-type-is-text

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

…es-when-enforce-type-is-json-in-unstract-but-the-same-works-fine-when-enforce-type-is-text
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
prompt-service/src/unstract/prompt_service/utils/json_repair_helper.py (1)

8-22: Consider more specific return type annotation.

The function returns Any which reduces type safety. Consider using a union type like dict[str, Any] | list[Any] | str to be more specific about possible return types.

-def repair_json_with_best_structure(json_str: str) -> Any:
+def repair_json_with_best_structure(json_str: str) -> dict[str, Any] | list[Any] | str:
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to Reviews > Disable Cache setting
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between bd9f0a6 and 43069f6.

📒 Files selected for processing (2)
  • prompt-service/src/unstract/prompt_service/services/answer_prompt.py (2 hunks)
  • prompt-service/src/unstract/prompt_service/utils/json_repair_helper.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (5)
prompt-service/src/unstract/prompt_service/utils/json_repair_helper.py (3)

44-49: LGTM! Excellent logic for detecting unnecessary array wrapping.

This condition correctly identifies when the array wrapping didn't provide additional value - when the wrapped result is just a single-element array containing the same data as the original parse.


56-58: LGTM! Smart detection of concatenated JSON objects.

This logic correctly identifies when the original string likely contained multiple comma-separated JSON objects (like {},{},{}) that were successfully parsed into a proper array structure through wrapping.


27-29: Validate json_repair behavior for wrapped arrays

The code prepends [ when calling repair_json. If the input is missing a closing bracket (or is otherwise malformed), this may still produce invalid JSON or unexpected results.

• Location: prompt-service/src/unstract/prompt_service/utils/json_repair_helper.py lines 27–29

parsed_with_wrap = repair_json(
    json_str="[" + json_str, return_objects=True, ensure_ascii=False
)

Please verify in your environment that json_repair correctly handles cases such as:

  • Input "{"key":"value"}" → yields [{"key":"value"}]
  • Input "{\"key\":\"value\"},{\"key2\":\"value2\"}" → yields [{"key":"value"},{"key2":"value2"}]
  • Completely malformed input (e.g. "invalid_json") raises an error or returns a well-defined fallback

If the library’s behavior isn’t as expected, add explicit validation or error handling around the wrapped string before parsing.

prompt-service/src/unstract/prompt_service/services/answer_prompt.py (2)

12-14: LGTM! Clean import of the new utility function.

The import is well-structured and follows good practices by importing only the specific function needed.


249-250: Confirm JSON repair behavior equivalence

I wasn’t able to locate the prior inline “repair” logic in this branch to compare against repair_json_with_best_structure. Please ensure the new utility truly matches the old behavior by:

  • Reviewing or adding unit tests for all edge cases previously handled (malformed objects, arrays, comma-separated entries).
  • Verifying that ensure_ascii=False and return_objects=True align with the former implementation’s semantics.
  • Running integration tests in prompt_service/services/answer_prompt.py to catch any downstream parsing issues.

Once covered by tests, this refactoring is safe and improves maintainability.

Copy link
Copy Markdown
Contributor

@harini-venkataraman harini-venkataraman left a comment

Choose a reason for hiding this comment

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

lgtm

Copy link
Copy Markdown
Contributor

@chandrasekharan-zipstack chandrasekharan-zipstack left a comment

Choose a reason for hiding this comment

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

LGTM - left some nit comments

…es-when-enforce-type-is-json-in-unstract-but-the-same-works-fine-when-enforce-type-is-text
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Aug 1, 2025

filepath function $$\textcolor{#23d18b}{\tt{passed}}$$ SUBTOTAL
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_logs}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_cleanup}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_cleanup\_skip}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_client\_init}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_get\_image\_exists}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_get\_image}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_get\_container\_run\_config}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_get\_container\_run\_config\_without\_mount}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_run\_container}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_get\_image\_for\_sidecar}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{runner/src/unstract/runner/clients/test\_docker.py}}$$ $$\textcolor{#23d18b}{\tt{test\_sidecar\_container}}$$ $$\textcolor{#23d18b}{\tt{1}}$$ $$\textcolor{#23d18b}{\tt{1}}$$
$$\textcolor{#23d18b}{\tt{TOTAL}}$$ $$\textcolor{#23d18b}{\tt{11}}$$ $$\textcolor{#23d18b}{\tt{11}}$$

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Aug 1, 2025

@Deepak-Kesavan
Copy link
Copy Markdown
Contributor Author

LGTM - left some nit comments

Will consider these changes later. Resolving it to unblock staging.

@vishnuszipstack vishnuszipstack merged commit c5b5f98 into main Aug 2, 2025
7 checks passed
@vishnuszipstack vishnuszipstack deleted the UN-2653-bug-rc-26-the-json-structure-collapses-when-enforce-type-is-json-in-unstract-but-the-same-works-fine-when-enforce-type-is-text branch August 2, 2025 04:34
pk-zipstack pushed a commit that referenced this pull request Aug 20, 2025
UN-2653 Fixed issue in JSON structure parsing

Signed-off-by: Deepak <89829542+Deepak-Kesavan@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants