Skip to content

Conversation

@vgrozdanic
Copy link
Member

Fix encrypted field metrics to properly send the table name in metric tags.

Problem

The encrypted field metrics were not sending the model/table name correctly. The metric tag used getattr(self, "_model_name", "unknown"), but _model_name was never being set, so all metrics showed "unknown" for the model name. Additionally, the tag was named "model" which is too generic.

Root Cause

The original code implemented __set_name__() to capture the model name, expecting Python's descriptor protocol to call it. However, Django's ModelBase metaclass removes fields from the class dict and stores them in _meta before Python can call __set_name__(). Django uses contribute_to_class() instead, which the encrypted field wasn't implementing.

Changes

  • Initialize _model_name in __init__ with default value "unknown" (for standalone field usage in tests)
  • Implement contribute_to_class() to capture the actual model name when field is added to a Django model
  • Change metric tag from "model" to "table_name" for better clarity
  • Add tests to verify metrics are sent with correct tags including table_name

Testing

Added two new tests:

  • test_encrypted_char_field_metrics_on_encrypt: Verifies encryption metrics have correct table_name tag
  • test_encrypted_char_field_metrics_on_decrypt: Verifies decryption metrics have correct table_name tag

All 68 encryption field tests pass.

Previously the model name was not being sent in metrics because:
- Used getattr(self, '_model_name', 'unknown') but _model_name was never set
- Field had __set_name__ but Django's ModelBase metaclass never calls it
- Django removes fields from class dict before Python can call __set_name__

Changes:
- Initialize _model_name in __init__ with 'unknown' default
- Implement contribute_to_class to capture actual model name
- Change metric tag from 'model' to 'table_name' for clarity
- Add tests to verify metrics are sent with correct table_name

All 68 encryption field tests pass.
@github-actions github-actions bot added the Scope: Backend Automatically applied to PRs that change backend components label Jan 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants