Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 3 additions & 2 deletions lean/components/cloud/cloud_project_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ def get_cloud_project_and_local_path(self, input: str, push: bool) -> Tuple[QCPr
local_path = Path.cwd() / input
if self._project_config_manager.try_get_project_config(local_path):
if push:
if not self._push_manager.push_projects([local_path]):
# Like `lean cloud push`, a library that cannot be pushed is only a warning
if not self._push_manager.push_project(local_path):
raise PushFailedError(input)

local_path = self._push_manager.pushed_project_paths[local_path]
Expand Down Expand Up @@ -111,7 +112,7 @@ def get_cloud_project_and_local_path(self, input: str, push: bool) -> Tuple[QCPr
if renamed_path and Path.cwd() in renamed_path.parents:
local_path = renamed_path
if local_path.exists():
if not self._push_manager.push_projects([local_path]):
if not self._push_manager.push_project(local_path):
raise PushFailedError(input)
return (self._api_client.projects.get(cloud_project.projectId, organization_id),
self._push_manager.pushed_project_paths[local_path])
Expand Down
22 changes: 16 additions & 6 deletions lean/components/cloud/pull_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,21 @@
from lean.models.encryption import ActionType
from lean.components.config.storage import safe_save


def get_pulled_file_content(cloud_file_content: str) -> str:
"""Returns the content a pull writes to the local drive for a cloud file's content.

:param cloud_file_content: the content of the file in the cloud
:return: the content with unix line endings, ending with a newline unless it is empty
"""
# Make sure we always work with unix line endings in memory,
# so they can be properly translated to the local OS line endings when writing to disk.
content = cloud_file_content.replace("\r\n", "\n")
if content != "" and not content.endswith("\n"):
content += "\n"
return content


class PullManager:
"""The PullManager class is responsible for synchronizing cloud projects to the local drive."""

Expand Down Expand Up @@ -239,12 +254,7 @@ def _pull_files(self, project: QCProject, local_project_path: Path, encryption_a

local_file_path.parent.mkdir(parents=True, exist_ok=True)

# Make sure we always work with unix line endings in memory,
# so they can be properly translated to the local OS line endings when writing to disk.
content = cloud_file.content.replace("\r\n", "\n")
if content != "" and not content.endswith("\n"):
content += "\n"
safe_save(content, local_file_path)
safe_save(get_pulled_file_content(cloud_file.content), local_file_path)

self._project_manager.update_last_modified_time(local_file_path, cloud_file.modified)
self._logger.info(f"Successfully pulled '{project.name}/{cloud_file.name}'")
Expand Down
67 changes: 55 additions & 12 deletions lean/components/cloud/push_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,17 @@ def __init__(self,
# Where each pushed project is after its push, which renames directories whose name is not valid locally or in the cloud
self.pushed_project_paths: Dict[Path, Path] = {}

def push_project(self, project: Path, encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> None:
def push_project(self, project: Path, encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> bool:
"""Pushes the given project from the local drive to the cloud.

It will also push every library referenced by the project and add or remove references.
A library that cannot be pushed only gets a warning, the project is pushed anyway.

:param project: path to the directory containing the local project that needs to be pushed
:return: True if the project was pushed, even when some of its libraries could not be
"""
libraries = self._project_manager.get_project_libraries(project)
self.push_projects([project], libraries, encryption_action, encryption_key, force)
return project not in self._push_projects([project], libraries, encryption_action, encryption_key, force)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Treat errors in dependency discovery and path formatting as library warnings when the main project can still resolve its references. A library with a valid cloud ID but a malformed nested reference raises during get_project_libraries() before the handler; a library symlinked outside the workspace raises at relative_to() before the handler too. The base resolver can push the main project in both cases. Keep per-library discovery errors isolated and use an absolute path fallback for logging.


def push_projects(self, projects_to_push: List[Path], associated_libraries_to_push: Optional[List[Path]]=[], encryption_action: Optional[ActionType]=None, encryption_key: Optional[Path]=None, force: Optional[bool]=False) -> bool:
"""Pushes the given projects from the local drive to the cloud.
Expand All @@ -72,12 +74,19 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu
:param projects_to_push: a list of directories containing the local projects that need to be pushed
:return: True if every project and library was pushed, False if any of them could not be pushed
"""
return len(self._push_projects(projects_to_push, associated_libraries_to_push, encryption_action,
encryption_key, force)) == 0

def _push_projects(self, projects_to_push: List[Path], associated_libraries_to_push: List[Path], encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool]) -> List[Path]:
"""Pushes the given projects and libraries, with a warning for each one that cannot be pushed.

:return: the directories of the projects and libraries that could not be pushed
"""
all_projects_to_push = associated_libraries_to_push + projects_to_push
failed_paths = []

if len(all_projects_to_push) == 0:
return True

all_pushed = True
return failed_paths

organization_id = self._organization_manager.try_get_working_organization_id()

Expand All @@ -89,17 +98,20 @@ def push_projects(self, projects_to_push: List[Path], associated_libraries_to_pu
relative_path = path.relative_to(Path.cwd())
try:
self._logger.info(f"[{index}/{len(all_projects_to_push)}] Pushing '{relative_path}'")
# A library whose cloud copy already matches the local one needs no update, so it is not
# rejected when the user can only read it.
self.pushed_project_paths[path] = self._push_project(path, organization_id, encryption_action_value,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The new path is recorded only after _push_project returns. With local Library/Café pointing to an existing read-only cloud library, the local rename to Library/Caf happens first. The rejected library write leaves the project config pointing at the missing Library/Café; the main push then fails reading its cloud ID. Record the move even when the cloud update fails, or roll it back, and test refused updates after a rename.

encryption_key_value, force=force)
encryption_key_value, force=force,
skip_if_unchanged=path in associated_libraries_to_push)
except Exception as ex:
from traceback import format_exc
self._logger.debug(format_exc().strip())
self._logger.warn(f"Cannot push '{relative_path}': {ex}")
if "write permission" in str(ex).lower():
self._logger.info("Please pull any required changes and push with --force")
all_pushed = False
failed_paths.append(path)

return all_pushed
return failed_paths

def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]:
project_config = self._project_config_manager.get_project_config(project_dir)
Expand Down Expand Up @@ -127,14 +139,15 @@ def _get_local_libraries_cloud_ids(self, project_dir: Path) -> List[int]:

return local_libraries_cloud_ids

def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None) -> Path:
def _push_project(self, project_path: Path, organization_id: str, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], suggested_rename_path: Path = None, skip_if_unchanged: bool = False) -> Path:
"""Pushes a single local project to the cloud.

Raises an error with a descriptive message if the project cannot be pushed.

:param project_path: the local project to push
:param organization_id: the id of the organization to push the project to
:param suggested_rename_path: the path to move the project to.
:param skip_if_unchanged: don't update the cloud project when it already matches the local one
:return: the path of the pushed project, which differs from project_path when the push renamed it
"""

Expand Down Expand Up @@ -198,7 +211,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act
if cloud_project.name != project_name:
# cloud project name was changed. Repeat steps to validate the new name locally.
self._logger.info(f"Received new name '{cloud_project.name}' for project '{project_name}' from QuantConnect.com")
return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name)
return self._push_project(project_path, organization_id, encryption_action, encryption_key, force, Path.cwd() / cloud_project.name, skip_if_unchanged)

self._cloud_projects.append(cloud_project)
organization_message_part = f" in organization '{organization_id}'" if organization_id is not None else ""
Expand All @@ -211,7 +224,7 @@ def _push_project(self, project_path: Path, organization_id: str, encryption_act
encryption_key = local_encryption_key
encryption_action = ActionType.ENCRYPT if local_encryption_state else ActionType.DECRYPT
# Finalize pushing by updating locally modified metadata, files and libraries
self._push_metadata(project_path, cloud_project, encryption_action, encryption_key, force)
self._push_metadata(project_path, cloud_project, encryption_action, encryption_key, force, skip_if_unchanged)
return project_path

def _get_files(self, project: Path, encryption_action: Optional[ActionType], encryption_key: Optional[Path]) -> List[Dict[str, str]]:
Expand Down Expand Up @@ -242,13 +255,14 @@ def _get_files(self, project: Path, encryption_action: Optional[ActionType], enc

return files

def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool]) -> None:
def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_action: Optional[ActionType], encryption_key: Optional[Path], force: Optional[bool], skip_if_unchanged: bool = False) -> None:
"""Pushes local project description and parameters to the cloud.

Does nothing if the cloud is already up-to-date.

:param project: the local project to push the parameters of
:param cloud_project: the cloud project to push the parameters to
:param skip_if_unchanged: return without updating when the cloud project already matches the local one
"""
project_config = self._project_config_manager.get_project_config(project)

Expand Down Expand Up @@ -304,6 +318,10 @@ def _push_metadata(self, project: Path, cloud_project: QCProject, encryption_act
encryption_key_id = get_project_key_hash(encryption_key)
update_args["encryption_key"] = encryption_key_id

if skip_if_unchanged and self._is_cloud_project_up_to_date(cloud_project, update_args, expected_correct_project_name):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please preserve the cloud library’s encryption state on an implicit push, even when the local copy differs. If it can’t be uploaded in that state, warn and leave the library untouched. Add a regression test for an encrypted cloud library with a differently configured local copy, asserting that no library write is sent.

self._logger.debug(f"'{cloud_project.name}' is already up to date in the cloud, not pushing it")
return

if not force:
update_args["code_source_id"] = "cli"
if update_args != {}:
Expand Down Expand Up @@ -382,6 +400,31 @@ def _push_one_by_one(self, cloud_project: QCProject, update_args: Dict[str, Any]
f"cloud project now mixes old and new code. Fix the problem and push again. "
f"Error: {error}") from error

def _is_cloud_project_up_to_date(self, cloud_project: QCProject, update_args: Dict, expected_name: str) -> bool:
"""Checks whether pushing update_args would leave the cloud project unchanged."""
changed_metadata = set(update_args) - {"name", "files", "libraries", "encryption_key"}
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved
if changed_metadata or cloud_project.name != expected_name or update_args["encryption_key"] != '':
return False

if set(update_args["libraries"]) != {library.projectId for library in cloud_project.libraries}:
return False

try:
# Library files come with their own names, and belong to the project's libraries, not to the project
cloud_files = {file.name: file.content for file in self._api_client.files.get_all(cloud_project.projectId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please use a non-mutating listing scoped to this library’s own files. files/read includes transitive files by default; dropping them after the response still downloads 55 library file sets for a chain of 10 unchanged libraries, instead of 10. Send includeLibraries=false for this comparison, and verify that the read leaves cloud files untouched.

if not file.isLibrary}
except Exception:
return False

local_files = {file["name"]: file["content"] for file in update_args["files"]}
if local_files.keys() != cloud_files.keys():
return False

# A file is unchanged when it is the one pushed, or the one a pull of the cloud copy wrote
from lean.components.cloud.pull_manager import get_pulled_file_content
return all(content in (cloud_files[name], get_pulled_file_content(cloud_files[name]))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

An unchanged file with identical # first\r\n# second bytes on both sides still triggers an update. Path.read_text() converts the local CRLF to LF without adding a final newline, so it matches neither raw cloud content nor the pull form (which adds a newline). Compare the cloud content using universal newlines before also checking the pull form, and test this exact-copy case.

for name, content in local_files.items())

def _get_cloud_project(self, project_id: int, organization_id: str) -> QCProject:
project = next(iter(p for p in self._cloud_projects if p.projectId == project_id), None)
if project is None:
Expand Down
8 changes: 4 additions & 4 deletions tests/commands/cloud/live/test_cloud_live_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,15 +206,15 @@ def test_cloud_live_deploy_offers_local_cash_for_resolved_project(project: str,
container.api_client.nodes.get_all.return_value = create_qc_nodes()
container.api_client.get.return_value = {"success": True, "status": "Undefined"}

def push_and_rename(paths):
paths[0].rename(resolved_path)
container.push_manager.pushed_project_paths[paths[0]] = resolved_path
def push_and_rename(path):
path.rename(resolved_path)
container.push_manager.pushed_project_paths[path] = resolved_path
return True

options = ["--push"] if push else []
# patch by module object: the dotted path resolves to the `cloud` click group on Python < 3.11
deploy_module = import_module("lean.commands.cloud.live.deploy")
with mock.patch.object(container.push_manager, "push_projects", side_effect=push_and_rename), \
with mock.patch.object(container.push_manager, "push_project", side_effect=push_and_rename), \
mock.patch.object(deploy_module, "configure_initial_cash_balance", return_value=[]) as configure_cash:
result = CliRunner().invoke(lean, ["cloud", "live", "deploy", project, *options, "--brokerage", "Paper Trading",
"--node", "live", "--auto-restart", "yes", "--notify-order-events", "no",
Expand Down
2 changes: 1 addition & 1 deletion tests/commands/cloud/test_backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def test_cloud_backtest_pushes_nothing_when_project_does_not_exist_locally() ->

assert result.exit_code == 0

push_manager.push_projects.assert_not_called()
push_manager.push_project.assert_not_called()


def test_cloud_backtest_aborts_when_push_of_project_with_cloud_id_fails() -> None:
Expand Down
2 changes: 1 addition & 1 deletion tests/commands/cloud/test_optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def test_cloud_optimize_pushes_nothing_when_project_does_not_exist_locally() ->

assert result.exit_code == 0

push_manager.push_projects.assert_not_called()
push_manager.push_project.assert_not_called()


def test_cloud_optimize_passes_given_config_to_cloud_runner() -> None:
Expand Down
Loading
Loading