-
Notifications
You must be signed in to change notification settings - Fork 358
fix!: make repr deterministic for fingerprinting #4925
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| """ | ||
| When serializing some objects, like `__sqlmesh__vars__`, the order of keys in the dictionary were not deterministic | ||
| and therefore this migration applies deterministic sorting to the keys of the dictionary. | ||
| """ | ||
|
|
||
| import json | ||
| import typing as t | ||
| from dataclasses import dataclass | ||
|
|
||
| from sqlglot import exp | ||
|
|
||
| from sqlmesh.utils.migration import index_text_type, blob_text_type | ||
|
|
||
|
|
||
| # Make sure `SqlValue` is defined so it can be used by `eval` call in the migration | ||
| @dataclass | ||
| class SqlValue: | ||
| """A SQL string representing a generated SQLGlot AST.""" | ||
|
|
||
| sql: str | ||
|
|
||
|
|
||
| def _deterministic_repr(obj: t.Any) -> str: | ||
| """ | ||
| This is a copy of the function from utils.metaprogramming | ||
| """ | ||
|
|
||
| def _normalize_for_repr(o: t.Any) -> t.Any: | ||
| if isinstance(o, dict): | ||
| sorted_items = sorted(o.items(), key=lambda x: str(x[0])) | ||
| return {k: _normalize_for_repr(v) for k, v in sorted_items} | ||
| if isinstance(o, (list, tuple)): | ||
| # Recursively normalize nested structures | ||
| normalized = [_normalize_for_repr(item) for item in o] | ||
| return type(o)(normalized) | ||
| return o | ||
|
|
||
| try: | ||
| return repr(_normalize_for_repr(obj)) | ||
| except Exception: | ||
| return repr(obj) | ||
|
|
||
|
|
||
| def migrate(state_sync, **kwargs): # type: ignore | ||
| import pandas as pd | ||
|
|
||
| engine_adapter = state_sync.engine_adapter | ||
| schema = state_sync.schema | ||
| snapshots_table = "_snapshots" | ||
| if schema: | ||
| snapshots_table = f"{schema}.{snapshots_table}" | ||
|
|
||
| migration_needed = False | ||
| new_snapshots = [] | ||
|
|
||
| for ( | ||
| name, | ||
| identifier, | ||
| version, | ||
| snapshot, | ||
| kind_name, | ||
| updated_ts, | ||
| unpaused_ts, | ||
| ttl_ms, | ||
| unrestorable, | ||
| ) in engine_adapter.fetchall( | ||
| exp.select( | ||
| "name", | ||
| "identifier", | ||
| "version", | ||
| "snapshot", | ||
| "kind_name", | ||
| "updated_ts", | ||
| "unpaused_ts", | ||
| "ttl_ms", | ||
| "unrestorable", | ||
| ).from_(snapshots_table), | ||
| quote_identifiers=True, | ||
| ): | ||
| parsed_snapshot = json.loads(snapshot) | ||
| python_env = parsed_snapshot["node"].get("python_env") | ||
|
|
||
| if python_env: | ||
| for key, executable in python_env.items(): | ||
| if isinstance(executable, dict) and executable.get("kind") == "value": | ||
| old_payload = executable["payload"] | ||
| try: | ||
| # Try to parse the old payload and re-serialize it deterministically | ||
| parsed_value = eval(old_payload) | ||
| new_payload = _deterministic_repr(parsed_value) | ||
|
|
||
| # Only update if the representation changed | ||
| if old_payload != new_payload: | ||
| executable["payload"] = new_payload | ||
| migration_needed = True | ||
| except Exception: | ||
| # If we still can't eval it, leave it as-is | ||
| pass | ||
|
|
||
| new_snapshots.append( | ||
| { | ||
| "name": name, | ||
| "identifier": identifier, | ||
| "version": version, | ||
| "snapshot": json.dumps(parsed_snapshot), | ||
| "kind_name": kind_name, | ||
| "updated_ts": updated_ts, | ||
| "unpaused_ts": unpaused_ts, | ||
| "ttl_ms": ttl_ms, | ||
| "unrestorable": unrestorable, | ||
| } | ||
| ) | ||
|
|
||
| if migration_needed and new_snapshots: | ||
| engine_adapter.delete_from(snapshots_table, "TRUE") | ||
|
|
||
| index_type = index_text_type(engine_adapter.dialect) | ||
| blob_type = blob_text_type(engine_adapter.dialect) | ||
|
|
||
| engine_adapter.insert_append( | ||
| snapshots_table, | ||
| pd.DataFrame(new_snapshots), | ||
| columns_to_types={ | ||
| "name": exp.DataType.build(index_type), | ||
| "identifier": exp.DataType.build(index_type), | ||
| "version": exp.DataType.build(index_type), | ||
| "snapshot": exp.DataType.build(blob_type), | ||
| "kind_name": exp.DataType.build("text"), | ||
| "updated_ts": exp.DataType.build("bigint"), | ||
| "unpaused_ts": exp.DataType.build("bigint"), | ||
| "ttl_ms": exp.DataType.build("bigint"), | ||
| "unrestorable": exp.DataType.build("boolean"), | ||
| }, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.