Skip to content
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

filesystem state sync #1184

Merged
merged 30 commits into from
Apr 17, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
0369496
clean some stuff
sh-rp Apr 3, 2024
9a87f0f
first messy version of filesystem state sync
sh-rp Apr 3, 2024
f6d5c9c
clean up a bit
sh-rp Apr 3, 2024
d58a38b
fix bug in state sync
sh-rp Apr 4, 2024
2913c33
enable state tests for all bucket providers
sh-rp Apr 4, 2024
e32ad95
do not store state to uninitialized dataset folders
sh-rp Apr 4, 2024
cd21ff6
fix linter errors
sh-rp Apr 4, 2024
6b7c16d
get current pipeline from pipeline context
sh-rp Apr 4, 2024
95cc882
fix bug in filesystem table init
sh-rp Apr 4, 2024
b5eb47d
Merge branch 'devel' into d#/filesystem_state_sync
sh-rp Apr 15, 2024
15ac9bf
update testing pipe
sh-rp Apr 15, 2024
a6ce1b1
move away from "current" file, rather iterator bucket path contents
sh-rp Apr 15, 2024
bce2837
store pipeline state in load package state and send to filesystem des…
sh-rp Apr 15, 2024
40f1f3e
fix tests for changed number of files in filesystem destination
sh-rp Apr 15, 2024
5e8c233
remove dev code
sh-rp Apr 15, 2024
e7e0192
create init file also to mark datasets
sh-rp Apr 15, 2024
7cd51b4
fix tests to respect new init file
sh-rp Apr 16, 2024
c406600
update filesystem docs
sh-rp Apr 16, 2024
0c52fcd
Merge branch 'devel' into d#/filesystem_state_sync
sh-rp Apr 16, 2024
f0635b2
fix incoming tests of placeholders
sh-rp Apr 16, 2024
bdaf094
small fixes
sh-rp Apr 16, 2024
a09f896
adds some tests for filesystem state
sh-rp Apr 16, 2024
fce47c6
fix test helper
sh-rp Apr 16, 2024
0d5423c
save schema with timestamp instead of load_id
sh-rp Apr 16, 2024
b2b5913
pr fixes and move pipeline state saving to committing of extracted pa…
sh-rp Apr 17, 2024
cd4dd23
ensure pipeline state is only saved to load package if it has changed
sh-rp Apr 17, 2024
c8b3429
adds missing state injection into state package
sh-rp Apr 17, 2024
6522f87
fix athena iceberg locations
sh-rp Apr 17, 2024
de34a48
fix google drive filesystem with missing argument
sh-rp Apr 17, 2024
abfc170
Merge branch 'devel' into d#/filesystem_state_sync
sh-rp Apr 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dlt/common/destination/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ def get_stored_schema(self) -> Optional[StorageSchemaInfo]:

@abstractmethod
def get_stored_schema_by_hash(self, version_hash: str) -> StorageSchemaInfo:
"""retrieves the stored schema by hash"""
pass

@abstractmethod
Expand Down
176 changes: 159 additions & 17 deletions dlt/destinations/impl/filesystem/filesystem.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import posixpath
import os
from types import TracebackType
from typing import ClassVar, List, Type, Iterable, Set, Iterator
from typing import ClassVar, List, Type, Iterable, Set, Iterator, Optional
from fsspec import AbstractFileSystem
from contextlib import contextmanager
from dlt.common import json, pendulum
from dlt.common.typing import DictStrAny

import re

from dlt.common import logger
from dlt.common.schema import Schema, TSchemaTables, TTableSchema
Expand All @@ -16,8 +20,12 @@
JobClientBase,
FollowupJob,
WithStagingDataset,
WithStateSync,
StorageSchemaInfo,
StateInfo,
DoNothingJob,
)

from dlt.common.destination.exceptions import DestinationUndefinedEntity
from dlt.destinations.job_impl import EmptyLoadJob
from dlt.destinations.impl.filesystem import capabilities
from dlt.destinations.impl.filesystem.configuration import FilesystemDestinationClientConfiguration
Expand Down Expand Up @@ -87,7 +95,7 @@ def create_followup_jobs(self, final_state: TLoadJobState) -> List[NewLoadJob]:
return jobs


class FilesystemClient(JobClientBase, WithStagingDataset):
class FilesystemClient(JobClientBase, WithStagingDataset, WithStateSync):
"""filesystem client storing jobs in memory"""

capabilities: ClassVar[DestinationCapabilitiesContext] = capabilities()
Expand Down Expand Up @@ -171,27 +179,44 @@ def update_stored_schema(
self, only_tables: Iterable[str] = None, expected_update: TSchemaTables = None
) -> TSchemaTables:
# create destination dirs for all tables
dirs_to_create = self._get_table_dirs(only_tables or self.schema.tables.keys())
for directory in dirs_to_create:
table_names = only_tables or self.schema.tables.keys()
dirs_to_create = self._get_table_dirs(table_names)
for tables_name, directory in zip(table_names, dirs_to_create):
self.fs_client.makedirs(directory, exist_ok=True)
# we need to mark the folders of the data tables as initialized
if tables_name in self.schema.dlt_table_names():
print(directory + " " + tables_name)
self.fs_client.touch(f"{directory}/init")

# write schema to destination
self.store_current_schema()

return expected_update

def _get_table_dirs(self, table_names: Iterable[str]) -> Set[str]:
def _get_table_dirs(self, table_names: Iterable[str]) -> List[str]:
"""Gets unique directories where table data is stored."""
table_dirs: Set[str] = set()
table_dirs: List[str] = []
rudolfix marked this conversation as resolved.
Show resolved Hide resolved
for table_name in table_names:
table_prefix = self.table_prefix_layout.format(
schema_name=self.schema.name, table_name=table_name
)
# dlt tables do not respect layout (for now)
if table_name in self.schema.dlt_table_names():
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it is totally fine and should stay like that (we need to document this)

table_prefix = posixpath.join(table_name, "")
else:
table_prefix = self.table_prefix_layout.format(
schema_name=self.schema.name, table_name=table_name
)
destination_dir = posixpath.join(self.dataset_path, table_prefix)
# extract the path component
table_dirs.add(os.path.dirname(destination_dir))
table_dirs.append(os.path.dirname(destination_dir))
return table_dirs

def is_storage_initialized(self) -> bool:
return self.fs_client.isdir(self.dataset_path) # type: ignore[no-any-return]

def start_file_load(self, table: TTableSchema, file_path: str, load_id: str) -> LoadJob:
# skip the state table, we create a jsonl file in the complete_load step
if table["name"] == self.schema.state_table_name:
return DoNothingJob(file_path)

cls = FollowupFilesystemJob if self.config.as_staging else LoadFilesystemJob
return cls(
file_path,
Expand All @@ -204,12 +229,6 @@ def start_file_load(self, table: TTableSchema, file_path: str, load_id: str) ->
def restore_file_load(self, file_path: str) -> LoadJob:
return EmptyLoadJob.from_file_path(file_path, "completed")

def complete_load(self, load_id: str) -> None:
schema_name = self.schema.name
table_name = self.schema.loads_table_name
file_name = f"{schema_name}.{table_name}.{load_id}"
self.fs_client.touch(posixpath.join(self.dataset_path, file_name))

def __enter__(self) -> "FilesystemClient":
return self

Expand All @@ -220,3 +239,126 @@ def __exit__(

def should_load_data_to_staging_dataset(self, table: TTableSchema) -> bool:
return False

#
# state stuff
#

def _write_to_json_file(self, filepath: str, data: DictStrAny) -> None:
dirname = os.path.dirname(filepath)
Copy link
Collaborator

Choose a reason for hiding this comment

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

don't use os.path, use posixpath. here paths are normalized from fsspec.

if not self.fs_client.isdir(dirname):
rudolfix marked this conversation as resolved.
Show resolved Hide resolved
return
self.fs_client.write_text(filepath, json.dumps(data), "utf-8")

def complete_load(self, load_id: str) -> None:
# store current state
self.store_current_state()

# write entry to load "table"
# TODO: this is also duplicate across all destinations. DRY this.
load_data = {
"load_id": load_id,
"schema_name": self.schema.name,
"status": 0,
"inserted_at": pendulum.now().isoformat(),
"schema_version_hash": self.schema.version_hash,
}
filepath = (
f"{self.dataset_path}/{self.schema.loads_table_name}/{self.schema.name}.{load_id}.jsonl"
Copy link
Collaborator

Choose a reason for hiding this comment

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

why this path? maybe we should save it where the previous path was

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i wanted to align it with the way all the other dlt tables are stored. i somehow like it more, we could have a setting though for backwards compatibility or something? your call.

)

self._write_to_json_file(filepath, load_data)

#
# state read/write
#

def _get_state_file_name(self, pipeline_name: str, version_hash: str) -> str:
"""gets full path for schema file for a given hash"""
safe_hash = "".join(
[c for c in version_hash if re.match(r"\w", c)]
) # remove all special chars from hash
return (
f"{self.dataset_path}/{self.schema.state_table_name}/{pipeline_name}__{safe_hash}.jsonl"
Copy link
Collaborator

Choose a reason for hiding this comment

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

hmmm you will not get same hash twice. we do not emit state if hash is not changing. also I think load_id is a must in the file name

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i put load id there now, not sure what you mean with the "you will not get the same hash twice" comment?

)

def store_current_state(self) -> None:
# get state doc from current pipeline
rudolfix marked this conversation as resolved.
Show resolved Hide resolved
from dlt.common.configuration.container import Container
from dlt.common.pipeline import PipelineContext
from dlt.pipeline.state_sync import state_doc

pipeline = Container()[PipelineContext].pipeline()
state = pipeline.state
doc = state_doc(state)

# get paths
current_path = self._get_state_file_name(pipeline.pipeline_name, "current")
Copy link
Collaborator

Choose a reason for hiding this comment

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

this will not work, yes we process package in order but do not assume that (because we do not have to)

Copy link
Collaborator Author

@sh-rp sh-rp Apr 15, 2024

Choose a reason for hiding this comment

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

I am not sure what you mean here, maybe we should discuss it briefly. Imho this setup replicates the behavior of the other destinations, with the same lookups/where clauses.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I have changed it to iterate over the files in the dir and select the correct one

hash_path = self._get_state_file_name(
pipeline.pipeline_name, self.schema.stored_version_hash
)

# write
self._write_to_json_file(current_path, doc)
self._write_to_json_file(hash_path, doc)

def get_stored_state(self, pipeline_name: str) -> Optional[StateInfo]:
# raise if dir not initialized
filepath = self._get_state_file_name(pipeline_name, "current")
Copy link
Collaborator

Choose a reason for hiding this comment

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

you need to reproduce the WHERE clause of other destinations.

  • must start with pipeline_name
  • find one with highest load_id and return

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This is what is does, no? I mean it starts with the pipeline name, so you can look up the state with the pipeline, and instead of looking for the highest load_id (which we shouldn't do anyway, since we should not rely on load ids being timestamps) it has this current marker. I have a screenshot above of the file layout this pr produces. This way we can avoid iterating through a list of files to find the newest one which will eventually slow down against destinations with many loads, at least that would be my expectation.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

changed this now.

dirname = os.path.dirname(filepath)
if not self.fs_client.isdir(dirname):
raise DestinationUndefinedEntity({"dir": dirname})

"""Loads compressed state from destination storage"""
if self.fs_client.exists(filepath):
state_json = json.loads(self.fs_client.read_text(filepath))
state_json.pop("version_hash")
return StateInfo(**state_json)

return None

#
# Schema read/write
#

def _get_schema_file_name(self, version_hash: str) -> str:
"""gets full path for schema file for a given hash"""
safe_hash = "".join(
[c for c in version_hash if re.match(r"\w", c)]
) # remove all special chars from hash
return f"{self.dataset_path}/{self.schema.version_table_name}/{self.schema.name}__{safe_hash}.jsonl"
Copy link
Collaborator

Choose a reason for hiding this comment

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

IMO hash is enough. also it would be good to have load_id

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I need the name in the filepath so I can find the right schema when looking for the newest version of a schema, so I will keep it.


def get_stored_schema(self) -> Optional[StorageSchemaInfo]:
"""Retrieves newest schema from destination storage"""
return self.get_stored_schema_by_hash("current")
Copy link
Collaborator

Choose a reason for hiding this comment

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

same thing like in state: find the oldest load id

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

done (assuming you mean the newest load id :) )


def get_stored_schema_by_hash(self, version_hash: str) -> Optional[StorageSchemaInfo]:
"""retrieves the stored schema by hash"""
filepath = self._get_schema_file_name(version_hash)
# raise if dir not initialized
dirname = os.path.dirname(filepath)
if not self.fs_client.isdir(dirname):
raise DestinationUndefinedEntity({"dir": dirname})
if self.fs_client.exists(filepath):
return StorageSchemaInfo(**json.loads(self.fs_client.read_text(filepath)))

return None

def store_current_schema(self) -> None:
# get paths
current_path = self._get_schema_file_name("current")
hash_path = self._get_schema_file_name(self.schema.stored_version_hash)

# TODO: duplicate of weaviate implementation, should be abstracted out
version_info = {
rudolfix marked this conversation as resolved.
Show resolved Hide resolved
"version_hash": self.schema.stored_version_hash,
"schema_name": self.schema.name,
"version": self.schema.version,
"engine_version": self.schema.ENGINE_VERSION,
"inserted_at": pendulum.now(),
"schema": json.dumps(self.schema.to_dict()),
}

# we always keep tabs on what the current schema is
self._write_to_json_file(current_path, version_info)
self._write_to_json_file(hash_path, version_info)
11 changes: 0 additions & 11 deletions dlt/destinations/impl/weaviate/weaviate_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,17 +521,6 @@ def get_stored_state(self, pipeline_name: str) -> Optional[StateInfo]:
state["dlt_load_id"] = state.pop("_dlt_load_id")
return StateInfo(**state)

# def get_stored_states(self, state_table: str) -> List[StateInfo]:
# state_records = self.get_records(state_table,
# sort={
# "path": ["created_at"],
# "order": "desc"
# }, properties=self.state_properties)

# for state in state_records:
# state["dlt_load_id"] = state.pop("_dlt_load_id")
# return [StateInfo(**state) for state in state_records]

def get_stored_schema(self) -> Optional[StorageSchemaInfo]:
"""Retrieves newest schema from destination storage"""
try:
Expand Down
9 changes: 0 additions & 9 deletions dlt/destinations/job_client_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,15 +371,6 @@ def get_stored_state(self, pipeline_name: str) -> StateInfo:
return None
return StateInfo(row[0], row[1], row[2], row[3], pendulum.instance(row[4]))

# def get_stored_states(self, state_table: str) -> List[StateInfo]:
# """Loads list of compressed states from destination storage, optionally filtered by pipeline name"""
# query = f"SELECT {self.STATE_TABLE_COLUMNS} FROM {state_table} AS s ORDER BY created_at DESC"
# result: List[StateInfo] = []
# with self.sql_client.execute_query(query) as cur:
# for row in cur.fetchall():
# result.append(StateInfo(row[0], row[1], row[2], row[3], pendulum.instance(row[4])))
# return result

def get_stored_schema_by_hash(self, version_hash: str) -> StorageSchemaInfo:
name = self.sql_client.make_qualified_table_name(self.schema.version_table_name)
query = f"SELECT {self.version_table_schema_columns} FROM {name} WHERE version_hash = %s;"
Expand Down
1 change: 0 additions & 1 deletion dlt/pipeline/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,6 @@ def sync_destination(
remote_state["schema_names"], always_download=True
)
# TODO: we should probably wipe out pipeline here

# if we didn't full refresh schemas, get only missing schemas
if restored_schemas is None:
restored_schemas = self._get_schemas_from_destination(
Expand Down
11 changes: 8 additions & 3 deletions dlt/pipeline/state_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,20 +115,25 @@ def migrate_pipeline_state(
return cast(TPipelineState, state)


def state_resource(state: TPipelineState) -> DltResource:
def state_doc(state: TPipelineState) -> DictStrAny:
state = copy(state)
state.pop("_local")
state_str = compress_state(state)
state_doc = {
doc = {
"version": state["_state_version"],
"engine_version": state["_state_engine_version"],
"pipeline_name": state["pipeline_name"],
"state": state_str,
"created_at": pendulum.now(),
"version_hash": state["_version_hash"],
}
return doc


def state_resource(state: TPipelineState) -> DltResource:
doc = state_doc(state)
return dlt.resource(
[state_doc], name=STATE_TABLE_NAME, write_disposition="append", columns=STATE_TABLE_COLUMNS
[doc], name=STATE_TABLE_NAME, write_disposition="append", columns=STATE_TABLE_COLUMNS
)


Expand Down
20 changes: 20 additions & 0 deletions fs_testing_pipe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import dlt
Copy link
Collaborator

Choose a reason for hiding this comment

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

keep those in some ignored folder ;)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yeah, i have that also, but since i am working on two different machines i need to do this sometimes ;)

import os

if __name__ == "__main__":
os.environ["DESTINATION__FILESYSTEM__BUCKET_URL"] = "file://my_files"
os.environ["DATA_WRITER__DISABLE_COMPRESSION"] = "TRUE"

# resource with incremental for testing restoring of pipeline state
@dlt.resource(name="my_table")
def my_resouce(id=dlt.sources.incremental("id")):
yield from [
{"id": 1},
{"id": 2},
{"id": 3},
{"id": 4},
{"id": 5}
]

pipe = dlt.pipeline(pipeline_name="dave", destination="filesystem")
pipe.run(my_resouce(), table_name="my_table") #, loader_file_format="parquet")
Loading
Loading