PictoPy icon indicating copy to clipboard operation
PictoPy copied to clipboard

BUG: Face cluster API returns metadata as JSON string instead of object

Open VasuS609 opened this issue 11 months ago • 13 comments

Is there an existing issue for this?

  • [x] I have searched the existing issues

What happened?

The GET /face-clusters/{id}/images endpoint returns image metadata as a serialized JSON string rather than a parsed object, violating the API schema contract and breaking client-side implementations.

Current Behavior

API Response: json{ "images": [ { "id": 123, "metadata": "{"camera":"Canon EOS","location":"NYC"}" } ] } Metadata is returned as a string Expected Behavior: json{ "images": [ { "id": 123, "metadata": { "camera": "Canon EOS", "location": "NYC" } } ] }

Metadata should be a proper JSON object Root Cause File: face_clusters.py Function: db_get_images_by_cluster_id (lines ~267-305) The function retrieves the metadata column directly from the database without deserializing it. Since most SQL databases store JSON as text, the raw string is passed through to the Pydantic response model, which expects a dictionary type. Steps to Reproduce

Insert a face record with JSON metadata:

sql INSERT INTO faces (cluster_id, image_id, metadata) VALUES (1, 100, '{"camera":"Canon EOS","location":"NYC"}');

Call the API endpoint:

bash curl http://localhost:8000/api/face-clusters/1/images

Observe the response contains stringified metadata instead of an object

Impact

API Contract Violation: Response doesn't match GetClusterImagesResponse schema Frontend Errors: Client code cannot access metadata.camera directly without additional parsing Type Safety: TypeScript/JavaScript clients receive incorrect types Test Failures: Unit tests expecting dict types will fail with string values

Proposed Solution Parse the metadata field before constructing the response: pythondef db_get_images_by_cluster_id(cluster_id: int): """Retrieve all images for a specific face cluster.""" cursor.execute(query, (cluster_id,)) images = []

for row in cursor.fetchall():
    # Deserialize metadata if stored as JSON string
    metadata = row['metadata']
    if metadata and isinstance(metadata, str):
        try:
            metadata = json.loads(metadata)
        except json.JSONDecodeError:
            logger.warning(f"Invalid JSON in metadata for image {row['id']}")
            metadata = None
    
    images.append({
        'id': row['id'],
        'metadata': metadata,  # Now properly typed as dict
        # ... other fields
    })

return images

Key improvements:

Handles both string and dict inputs (database-agnostic) Graceful error handling for malformed JSON Logging for debugging Maintains backward compatibility

Alternative approach: If there's an existing utility function like parse_metadata() in the codebase, we should use that for consistency: pythonfrom utils.image_utils import parse_metadata

metadata = parse_metadata(row['metadata'])

Testing Plan

Unit test: metadata stored as JSON string is correctly parsed Unit test: metadata already as dict passes through unchanged Unit test: invalid JSON is handled gracefully (returns null/empty dict) Integration test: API response validation passes Verify existing tests in test_face_clusters.py still pass

Files to Modify

backend/face_clusters.py (primary fix) tests/test_face_clusters.py (add test cases)

Additional Context This is a common issue when working with JSON columns in SQL databases. SQLite stores JSON as TEXT, PostgreSQL has native JSON support but can return strings depending on the driver configuration. The fix ensures consistent behavior across database backends.

I'd be happy to submit a PR with the fix and comprehensive tests! Let me know if you'd prefer a specific approach or if there are existing utilities I should use.

Record

  • [x] I agree to follow this project's Code of Conduct

Checklist before Submitting

  • [x] Have you updated docs for it?
  • [x] Have you added unit tests?
  • [ ] Have you made sure unit tests pass?
  • [x] Have you made sure code formatting is correct?
  • [ ] Do Your changes passes all tests?

VasuS609 avatar Dec 10 '25 13:12 VasuS609

Hi, I’d like to work on this issue. From what I understand, the API is currently returning the metadata field as a JSON-encoded string instead of a proper object. I plan to trace where the response is being serialized and update it so the metadata is returned as a native JSON object consistently. Please let me know if that approach sounds good.

shagunbhadouria avatar Dec 22 '25 18:12 shagunbhadouria

Hi maintainers, I would like to work on this issue. Please assign it to me.

Thank you!

lucifer13598 avatar Dec 27 '25 04:12 lucifer13598

Hey @rahulharpal1603, pls have a look on my PR https://github.com/AOSSIE-Org/PictoPy/pull/707

VasuS609 avatar Jan 02 '26 20:01 VasuS609

Hi, I would like to work on this issue.

I reviewed the current implementation of db_get_images_by_cluster_id and noticed that the metadata field is already being deserialized using:

metadata_dict = json.loads(metadata) if metadata else None

Given this, I would like to clarify where the serialization mismatch is occurring.

From this function alone, metadata should already be returned as a dictionary when valid JSON is stored in the database.

Could this issue be happening in one of the following cases?

  • metadata is already a dict in some scenarios and gets re-serialized later
  • Invalid or malformed JSON is stored in certain rows
  • The response model or another layer re-serializes the field
  • The behavior differs across database backends

I’d like to confirm the exact reproduction context before proceeding with changes, to ensure the fix is applied at the correct layer.

RiddhiPachehara avatar Feb 19 '26 15:02 RiddhiPachehara

it is assigned to me bro

JITENDRAGAHERWAR03 avatar Feb 23 '26 14:02 JITENDRAGAHERWAR03

@JITENDRAGAHERWAR03 Thanks for the clarification :) I’ll step back from this issue. If there are related areas where additional tests or improvements are needed, I’d be happy to contribute.

RiddhiPachehara avatar Feb 23 '26 15:02 RiddhiPachehara

Hi! I would like to work on this issue. Could you please assign it to me?

amishikaushal avatar Mar 11 '26 10:03 amishikaushal

修复方案可以考虑两种情况:1) 数据库层:在查询时用SQL的JSON_EXTRACT或应用层json.loads;2) Pydantic层:用validator装饰器自动解析。推荐方案1+在model层加fallback,因为数据库驱动返回类型可能不一致。测试时注意mock cursor返回str和dict两种情况。

passionworkeer avatar Mar 11 '26 10:03 passionworkeer

Hi! I'm Harjit (GitHub: nonehxrry), a GSoC 2026 applicant interested in PictoPy. I'd like to work on this bug. I'll fix the face cluster API to return metadata as a proper JSON object instead of a string. Is this still available?

nonehxrry avatar Mar 21 '26 14:03 nonehxrry

"Hi! I looked at the current code and db_get_images_by_cluster_id already has json.loads() for metadata parsing, but it's missing error handling , if metadata contains invalid JSON it will crash. I'd like to fix this and add tests to cover all cases. Can I work on this?"

Manasvibansal1 avatar Jun 26 '26 10:06 Manasvibansal1

I've submitted PR #1344 which fixes this issue by adding metadata JSON parsing with proper error handling. All 30 tests passing. Please review when you get a chance! Thankyou!

Manasvibansal1 avatar Jun 26 '26 10:06 Manasvibansal1

can you assign this to me?

yashchaurasia667 avatar Oct 11 '26 17:10 yashchaurasia667

Hi @VasuS609,

I'd like to contribute to this issue and work on fixing the metadata parsing problem in the GET /face-clusters/{id}/images endpoint.

I plan to investigate the existing implementation in backend/face_clusters.py, implement a robust solution for handling JSON metadata, and add unit tests to cover valid JSON strings, dictionary inputs, and malformed JSON.

Before I get started, could you please let me know if anyone is already working on this issue? I'd be happy to take it up and submit a PR following the project's contribution guidelines.

Thank you!

CSV2005 avatar Oct 20 '26 11:10 CSV2005