internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: dbt-labs/dbt-core

Issue:
[CT-1201] [Bug] Metrics don't require `expression` field
### Is this a new bug in dbt-core?

- [X] I believe this is a new bug in dbt-core
- [X] I have searched the existing issues, and I could not find an existing issue for this bug

### Current Behavior

Ran into this behavior when working with a beta customer. Right now, we provide the default value of empty string ("") to the expression/sql field. That then gets provided to ParsedMetric where it recognizes this field as a string and accepts it, even if the field isn't defined in the metric.

### Expected Behavior

If the expression field isn't present, the metric would fail to compile.

### Steps To Reproduce

1. Create a metric without a sql/expression field
2. Compile/parse



Discussion:

Resolving patch:
diff --git a/core/dbt/contracts/graph/parsed.py b/core/dbt/contracts/graph/parsed.py
--- a/core/dbt/contracts/graph/parsed.py
+++ b/core/dbt/contracts/graph/parsed.py
@@ -819,8 +819,8 @@ class ParsedMetric(UnparsedBaseNode, HasUniqueID, HasFqn):
     description: str
     label: str
     calculation_method: str
-    expression: str
     timestamp: str
+    expression: str
     filters: List[MetricFilter]
     time_grains: List[str]
     dimensions: List[str]
diff --git a/core/dbt/contracts/graph/unparsed.py b/core/dbt/contracts/graph/unparsed.py
--- a/core/dbt/contracts/graph/unparsed.py
+++ b/core/dbt/contracts/graph/unparsed.py
@@ -475,8 +475,8 @@ class UnparsedMetric(dbtClassMixin, Replaceable):
     label: str
     calculation_method: str
     timestamp: str
+    expression: str
     description: str = ""
-    expression: Union[str, int] = ""
     time_grains: List[str] = field(default_factory=list)
     dimensions: List[str] = field(default_factory=list)
     window: Optional[MetricTime] = None


Test patch:
diff --git a/tests/functional/metrics/test_metrics.py b/tests/functional/metrics/test_metrics.py
--- a/tests/functional/metrics/test_metrics.py
+++ b/tests/functional/metrics/test_metrics.py
@@ -196,6 +196,42 @@ def test_simple_metric(
             run_dbt(["run"])
 
 
+invalid_metrics__missing_expression_yml = """
+version: 2
+metrics:
+  - name: number_of_people
+    label: "Number of people"
+    model: "ref(people)"
+    description: Total count of people
+    calculation_method: count
+    timestamp: created_at
+    time_grains: [day, week, month]
+    dimensions:
+      - favorite_color
+      - loves_dbt
+    meta:
+        my_meta: 'testing'
+"""
+
+
+class TestInvalidMetricMissingExpression:
+    @pytest.fixture(scope="class")
+    def models(self):
+        return {
+            "people_metrics.yml": invalid_metrics__missing_expression_yml,
+            "people.sql": models__people_sql,
+        }
+
+    # tests that we get a ParsingException with a missing expression
+    def test_simple_metric(
+        self,
+        project,
+    ):
+        # initial run
+        with pytest.raises(ParsingException):
+            run_dbt(["run"])
+
+
 names_with_spaces_metrics_yml = """
 version: 2
Repository: dbt-labs/dbt-core

Issue:
[CT-1239] [Feature] Allow partitions in external tables to be supplied as a list
### Is this your first time submitting a feature request?

- [X] I have read the [expectations for open source contributors](https://docs.getdbt.com/docs/contributing/oss-expectations)
- [X] I have searched the existing issues, and I could not find an existing issue for this feature
- [X] I am requesting a straightforward extension of existing dbt functionality, rather than a Big Idea better suited to a discussion

### Describe the feature

Partitions in external tables can be supplied as a list (currently a name and data type are the minimum requirements).

### Describe alternatives you've considered

Supplying a list of partitions with `name` and `data_type` values is superfluous, especially the `data_type` as this is not used. While specifying the partitions in this way works, it is not a great user experiences.

### Who will this benefit?

Users of the `dbt-external-tables` package that have a Spark/Databricks connection.

### Are you interested in contributing this feature?

Yes.

### Anything else?

Background can be found in this [comment](https://github.com/dbt-labs/dbt-external-tables/pull/161#issuecomment-1255940060) on a PR for `dbt-external-tables`.


Discussion:

Resolving patch:
diff --git a/core/dbt/contracts/graph/unparsed.py b/core/dbt/contracts/graph/unparsed.py
--- a/core/dbt/contracts/graph/unparsed.py
+++ b/core/dbt/contracts/graph/unparsed.py
@@ -232,7 +232,7 @@ class ExternalTable(AdditionalPropertiesAllowed, Mergeable):
     file_format: Optional[str] = None
     row_format: Optional[str] = None
     tbl_properties: Optional[str] = None
-    partitions: Optional[List[ExternalPartition]] = None
+    partitions: Optional[Union[List[str], List[ExternalPartition]]] = None
 
     def __bool__(self):
         return self.location is not None


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-564] [Bug] Fix `parser/sources.py` mypy errors
This ticket encompasses the work to fix mypy errors in `core/dbt/parser/sources.py` on line 66.  Mypy thinks all code below the `continue` is unreachable due to type mutation in the parsing process (mutates from unpatched to parsed)
 Search `sources.py` for this ticket number to find the lines that trigger the warning.


Discussion:

Resolving patch:
diff --git a/core/dbt/parser/sources.py b/core/dbt/parser/sources.py
--- a/core/dbt/parser/sources.py
+++ b/core/dbt/parser/sources.py
@@ -63,7 +63,7 @@ def construct_sources(self) -> None:
                 self.sources[unpatched.unique_id] = unpatched
                 continue
             # returns None if there is no patch
-            patch = self.get_patch_for(unpatched)  # type: ignore[unreachable] # CT-564 / GH 5169
+            patch = self.get_patch_for(unpatched)
 
             # returns unpatched if there is no patch
             patched = self.patch_source(unpatched, patch)
@@ -213,8 +213,8 @@ def get_patch_for(
         self,
         unpatched: UnpatchedSourceDefinition,
     ) -> Optional[SourcePatch]:
-        if isinstance(unpatched, ParsedSourceDefinition):  # type: ignore[unreachable] # CT-564 / GH 5169
-            return None  # type: ignore[unreachable] # CT-564 / GH 5169
+        if isinstance(unpatched, ParsedSourceDefinition):
+            return None
         key = (unpatched.package_name, unpatched.source.name)
         patch: Optional[SourcePatch] = self.manifest.source_patches.get(key)
         if patch is None:


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1285] [Feature] extend `-f` flag shorthand to other commands 
### Is this your first time submitting a feature request?

- [X] I have read the [expectations for open source contributors](https://docs.getdbt.com/docs/contributing/oss-expectations)
- [X] I have searched the existing issues, and I could not find an existing issue for this feature
- [X] I am requesting a straightforward extension of existing dbt functionality, rather than a Big Idea better suited to a discussion

### Describe the feature

PR #5908 added the `-f` shorthand for `--full-refresh`, but I accidentally only allowed it for the `dbt build` command. This shoul dbe extended to `dbt seed` and `dbt run` and ot any other command that takes `--full-refresh`

### Describe alternatives you've considered

NA

### Who will this benefit?

typers

### Are you interested in contributing this feature?

yes

### Anything else?

_No response_


Discussion:

Resolving patch:
diff --git a/core/dbt/main.py b/core/dbt/main.py
--- a/core/dbt/main.py
+++ b/core/dbt/main.py
@@ -687,6 +687,7 @@ def _build_seed_subparser(subparsers, base_subparser):
     )
     seed_sub.add_argument(
         "--full-refresh",
+        "-f",
         action="store_true",
         help="""
         Drop existing seed tables and recreate them


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1337] [Bug] dbt is writing `target/partial_parse.msgpack` in current working directory and not using config's project-dir
### Is this a new bug in dbt-core?

- [X] I believe this is a new bug in dbt-core
- [X] I have searched the existing issues, and I could not find an existing issue for this bug

### Current Behavior

This [line](https://github.com/dbt-labs/dbt-core/blob/558468e85480c2f25fa7742d7d3d54ee813524d1/core/dbt/parser/manifest.py#L546) is creating a new relative path to the `target` folder instead of an absolute path as [this line](https://github.com/dbt-labs/dbt-core/blob/558468e85480c2f25fa7742d7d3d54ee813524d1/core/dbt/parser/manifest.py#L643) is correctly doing.


### Expected Behavior

To store `partial_parse.msgpack` in the right folder. Right now, it could create it in current working directory instead of `project-dir`.

### Steps To Reproduce

Couldn't find a way to reproduce it using dbt commands. It is happening on [sqlfluff dbt templater](https://github.com/sqlfluff/sqlfluff) when using `dbt.parser.manifest` to read manifest.

### Relevant log output

_No response_

### Environment

```markdown
- OS: any
- Python: 3.8
- dbt: 1.3
```


### Which database adapter are you using with dbt?

postgres, redshift, snowflake, bigquery, spark

### Additional Context

_No response_


Discussion:
(I accidentally left a comment here intended for https://github.com/dbt-labs/dbt-snowflake/issues/296. Too many tabs open!)

Thanks for opening @ssassi, and pointing to the specific line of code. This sounds like a straightforward bug.

Resolving patch:
diff --git a/core/dbt/parser/manifest.py b/core/dbt/parser/manifest.py
--- a/core/dbt/parser/manifest.py
+++ b/core/dbt/parser/manifest.py
@@ -537,7 +537,9 @@ def macro_depends_on(self):
                     macro.depends_on.add_macro(dep_macro_id)  # will check for dupes
 
     def write_manifest_for_partial_parse(self):
-        path = os.path.join(self.root_project.target_path, PARTIAL_PARSE_FILE_NAME)
+        path = os.path.join(
+            self.root_project.project_root, self.root_project.target_path, PARTIAL_PARSE_FILE_NAME
+        )
         try:
             # This shouldn't be necessary, but we have gotten bug reports (#3757) of the
             # saved manifest not matching the code version.


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1252] [Feature] Create GHA to autogenerate documentation using Sphinx
### Describe the feature
This is the next step after this ticket https://github.com/dbt-labs/dbt-core/issues/5528

After we have Sphinx configured and able to generate documentation for our future APIs, we want to be able to automate this by using GitHub Actions.

Exit criteria: a GitHub Action that-
* you can trigger manually or on a push to `main` or release branches
* the documentation is uploaded as an artifact of the run

Future work out of scope for this:
* Uploading docs to during to our GitHub Release automatically
* Leveraging these docs in the docs website



Discussion:

Resolving patch:
diff --git a/core/dbt/docs/source/conf.py b/core/dbt/docs/source/conf.py
--- a/core/dbt/docs/source/conf.py
+++ b/core/dbt/docs/source/conf.py
@@ -7,7 +7,7 @@
 # For the full list of built-in configuration values, see the documentation:
 # https://www.sphinx-doc.org/en/master/usage/configuration.html
 
-sys.path.insert(0, os.path.abspath("../.."))
+sys.path.insert(0, os.path.abspath("../../.."))
 sys.path.insert(0, os.path.abspath("./_ext"))
 
 # -- Project information -----------------------------------------------------


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1468] [Feature] Use new profile name handling in lib file for dbt-server
### Is this your first time submitting a feature request?

- [X] I have read the [expectations for open source contributors](https://docs.getdbt.com/docs/contributing/oss-expectations)
- [X] I have searched the existing issues, and I could not find an existing issue for this feature
- [X] I am requesting a straightforward extension of existing dbt functionality, rather than a Big Idea better suited to a discussion

### Describe the feature

In order to dynamically pass a profile name to RuntimeConfig creation from the dbt-server, we want to make use of the refactor made [in this branch](https://github.com/dbt-labs/dbt-core/pull/6157).

I (@racheldaniel ) have made these changes already and am creating this ticket to associate with my PR.

This will only affect the `lib.py` file currently in use by the dbt-server.

### Describe alternatives you've considered

Eventually we will pass this via new core API-- this is a stopgap to resolve some errors we're creating by manually rewriting users' dbt_project.yml in the Semantic Layer workflow.

### Who will this benefit?

_No response_

### Are you interested in contributing this feature?

_No response_

### Anything else?

_No response_


Discussion:

Resolving patch:
diff --git a/core/dbt/lib.py b/core/dbt/lib.py
--- a/core/dbt/lib.py
+++ b/core/dbt/lib.py
@@ -1,4 +1,6 @@
 import os
+from dbt.config.project import Project
+from dbt.config.renderer import DbtProjectYamlRenderer
 from dbt.contracts.results import RunningStatus, collect_timing_info
 from dbt.events.functions import fire_event
 from dbt.events.types import NodeCompiling, NodeExecuting
@@ -71,16 +73,22 @@ def get_dbt_config(project_dir, args=None, single_threaded=False):
     else:
         profiles_dir = flags.DEFAULT_PROFILES_DIR
 
+    profile_name = getattr(args, "profile", None)
+
     runtime_args = RuntimeArgs(
         project_dir=project_dir,
         profiles_dir=profiles_dir,
         single_threaded=single_threaded,
-        profile=getattr(args, "profile", None),
+        profile=profile_name,
         target=getattr(args, "target", None),
     )
 
-    # Construct a RuntimeConfig from phony args
-    config = RuntimeConfig.from_args(runtime_args)
+    profile = RuntimeConfig.collect_profile(args=runtime_args, profile_name=profile_name)
+    project_renderer = DbtProjectYamlRenderer(profile, None)
+    project = RuntimeConfig.collect_project(args=runtime_args, project_renderer=project_renderer)
+    assert type(project) is Project
+
+    config = RuntimeConfig.from_parts(project, profile, runtime_args)
 
     # Set global flags from arguments
     flags.set_from_args(args, config)


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1502] [Feature] Add md5 function to the jinja context
### Is this your first time submitting a feature request?

- [X] I have read the [expectations for open source contributors](https://docs.getdbt.com/docs/contributing/oss-expectations)
- [X] I have searched the existing issues, and I could not find an existing issue for this feature
- [X] I am requesting a straightforward extension of existing dbt functionality, rather than a Big Idea better suited to a discussion

### Describe the feature

I would like to add a simple md5 function to the base context, so it can be used in macros / models / tests.

### Describe alternatives you've considered

_No response_

### Who will this benefit?

The main use case we have in mind is performance-related - we have a relatively slow computation that we want to avoid repeating on every run.
In order to do this we want to be able to compute an MD5 locally and compare it to an MD5 stored in the database, and only perform the computation if the values are different.

### Are you interested in contributing this feature?

Yes, I will submit a PR following the submission of this issue

### Anything else?

_No response_


Discussion:

Resolving patch:
diff --git a/core/dbt/context/base.py b/core/dbt/context/base.py
--- a/core/dbt/context/base.py
+++ b/core/dbt/context/base.py
@@ -4,6 +4,7 @@
 
 from dbt import flags
 from dbt import tracking
+from dbt import utils
 from dbt.clients.jinja import get_rendered
 from dbt.clients.yaml_helper import yaml, safe_load, SafeLoader, Loader, Dumper  # noqa: F401
 from dbt.constants import SECRET_ENV_PREFIX, DEFAULT_ENV_PLACEHOLDER
@@ -687,6 +688,19 @@ def diff_of_two_dicts(
                 dict_diff.update({k: dict_a[k]})
         return dict_diff
 
+    @contextmember
+    @staticmethod
+    def local_md5(value: str) -> str:
+        """Calculates an MD5 hash of the given string.
+        It's called "local_md5" to emphasize that it runs locally in dbt (in jinja context) and not an MD5 SQL command.
+
+        :param value: The value to hash
+
+        Usage:
+            {% set value_hash = local_md5("hello world") %}
+        """
+        return utils.md5(value)
+
 
 def generate_base_context(cli_vars: Dict[str, Any]) -> Dict[str, Any]:
     ctx = BaseContext(cli_vars)


Test patch:
diff --git a/test/unit/test_context.py b/test/unit/test_context.py
--- a/test/unit/test_context.py
+++ b/test/unit/test_context.py
@@ -201,6 +201,7 @@ def assert_has_keys(required_keys: Set[str], maybe_keys: Set[str], ctx: Dict[str
         "flags",
         "print",
         "diff_of_two_dicts",
+        "local_md5"
     }
 )
Repository: dbt-labs/dbt-core

Issue:
[CT-1501] Clarify Error Message for how many models are allowed in a Python file
Currrently, if you have less than or more than one python model in a file, a parsing error reads:

> dbt only allow one model defined per python file

but that's not clearly capturing the case where you have less than one model per python file. 

https://github.com/dbt-labs/dbt-core/blob/dcd6ef733b4665393e2bef09ae4a2e542692f28e/core/dbt/parser/models.py#L63-L64

Suggest setting the error to:
> dbt allows exactly one model defined per python file, found `<x>` 


Discussion:

Resolving patch:
diff --git a/core/dbt/parser/models.py b/core/dbt/parser/models.py
--- a/core/dbt/parser/models.py
+++ b/core/dbt/parser/models.py
@@ -61,7 +61,11 @@ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
 
     def check_error(self, node):
         if self.num_model_def != 1:
-            raise ParsingException("dbt only allow one model defined per python file", node=node)
+            raise ParsingException(
+                f"dbt allows exactly one model defined per python file, found {self.num_model_def}",
+                node=node,
+            )
+
         if len(self.dbt_errors) != 0:
             raise ParsingException("\n".join(self.dbt_errors), node=node)
 


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1541] Regression in logic for "selection criterion ... does not match any nodes"
Petit regression in the `main` branch, introduced by https://github.com/dbt-labs/dbt-core/pull/6064

Caught by Sung in https://github.com/dbt-labs/dbt-core/pull/6271#discussion_r1026900579, and Mila in Slack

### Before

https://github.com/dbt-labs/dbt-core/blob/8145eed603266951ce35858f7eef3836012090bd/core/dbt/graph/selector.py#L145-L146

https://github.com/dbt-labs/dbt-core/blob/8145eed603266951ce35858f7eef3836012090bd/core/dbt/graph/selector.py#L27-L29

### After

https://github.com/dbt-labs/dbt-core/blob/987764858b81b95d8b93dcce67a4a9aace532ba3/core/dbt/graph/selector.py#L139-L140

(missing the check for `len(direct_nodes) == 0`!)


Discussion:

Resolving patch:
diff --git a/core/dbt/graph/selector.py b/core/dbt/graph/selector.py
--- a/core/dbt/graph/selector.py
+++ b/core/dbt/graph/selector.py
@@ -136,7 +136,7 @@ def select_nodes_recursively(self, spec: SelectionSpec) -> Tuple[Set[UniqueId],
 
             direct_nodes = self.incorporate_indirect_nodes(initial_direct, indirect_nodes)
 
-            if spec.expect_exists:
+            if spec.expect_exists and len(direct_nodes) == 0:
                 warn_or_error(NoNodesForSelectionCriteria(spec_raw=str(spec.raw)))
 
         return direct_nodes, indirect_nodes


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1659] Add Optional back to "database" field in HasRelationMetadata
In the refactoring of the manifest nodes that was committed, the "Optional" on database in HasRelationMetadata was inadvertently removed. Put it back.


Discussion:

Resolving patch:
diff --git a/core/dbt/contracts/graph/nodes.py b/core/dbt/contracts/graph/nodes.py
--- a/core/dbt/contracts/graph/nodes.py
+++ b/core/dbt/contracts/graph/nodes.py
@@ -152,7 +152,7 @@ class ColumnInfo(AdditionalPropertiesMixin, ExtensibleDbtClassMixin, Replaceable
 # Metrics, exposures,
 @dataclass
 class HasRelationMetadata(dbtClassMixin, Replaceable):
-    database: str
+    database: Optional[str]
     schema: str
 
     # Can't set database to None like it ought to be


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1752] [Bug] Small typos related to the interactive profile set up
### Is this a new bug in dbt-core?

- [X] I believe this is a new bug in dbt-core
- [X] I have searched the existing issues, and I could not find an existing issue for this bug

### Current Behavior

I believe `interative` is a typo of `interactive`

https://github.com/dbt-labs/dbt-core/blob/54538409509e0d677876f1102aa3bc0c67007278/core/dbt/cli/params.py#L272-L274
https://github.com/dbt-labs/dbt-core/blob/60f80056b1b09b35a22ac91c93319827bdac0e0e/core/dbt/main.py#L348-L356
https://github.com/dbt-labs/dbt-core/blob/b3440417ad1e38a40c488c3632a63f5d2e0c88f4/core/dbt/docs/build/html/index.html#L321-L325

### Expected Behavior

Fix typos:

-  `interative` to `interactive`

### Steps To Reproduce

1. Run `dbt init --h` 

### Relevant log output

```shell
N/A
```


### Environment

```markdown
- OS:Ubuntu 22.04.1
- Python: 3.10.6
- dbt: 1.1.3
```


### Which database adapter are you using with dbt?

_No response_

### Additional Context

N/A


Discussion:

Resolving patch:
diff --git a/core/dbt/cli/params.py b/core/dbt/cli/params.py
--- a/core/dbt/cli/params.py
+++ b/core/dbt/cli/params.py
@@ -270,7 +270,7 @@
 )
 
 skip_profile_setup = click.option(
-    "--skip-profile-setup", "-s", envvar=None, help="Skip interative profile setup.", is_flag=True
+    "--skip-profile-setup", "-s", envvar=None, help="Skip interactive profile setup.", is_flag=True
 )
 
 # TODO:  The env var and name (reflected in flags) are corrections!
diff --git a/core/dbt/main.py b/core/dbt/main.py
--- a/core/dbt/main.py
+++ b/core/dbt/main.py
@@ -351,7 +351,7 @@ def _build_init_subparser(subparsers, base_subparser):
         dest="skip_profile_setup",
         action="store_true",
         help="""
-        Skip interative profile setup.
+        Skip interactive profile setup.
         """,
     )
     sub.set_defaults(cls=init_task.InitTask, which="init", rpc_method=None)


Test patch:
Repository: dbt-labs/dbt-core

Issue:
[CT-1745] Reword deprecation message for metric attribute rename
After discussion with @callum-mcdata, let's pause on removing the deprecation warning & backwards compatibility for now, given greater changes that we're envisioning for the metrics spec in the next few versions (e.g. #6379).

In the meantime, let's just update the deprecation warning to replace "in v1.4" with "in a future version":

https://github.com/dbt-labs/dbt-core/blob/fafd5edbda2e94e6452bf2487fffee6e267736b1/core/dbt/events/types.py#L395

_Originally posted by @jtcohen6 in https://github.com/dbt-labs/dbt-core/issues/5849#issuecomment-1370703839_
      


Discussion:
@jtcohen6 want me to handle updating the message? I had it on my to-do list for today but if you've got a handle on it I'm happy to step back! 
@callum-mcdata all yours! (& thank you!)

Resolving patch:
diff --git a/core/dbt/events/types.py b/core/dbt/events/types.py
--- a/core/dbt/events/types.py
+++ b/core/dbt/events/types.py
@@ -392,7 +392,6 @@ def message(self):
             "\n  'sql'              -> 'expression'"
             "\n  'type'             -> 'calculation_method'"
             "\n  'type: expression' -> 'calculation_method: derived'"
-            "\nThe old metric parameter names will be fully deprecated in v1.4."
             f"\nPlease remove them from the metric definition of metric '{self.metric_name}'"
             "\nRelevant issue here: https://github.com/dbt-labs/dbt-core/issues/5849"
         )


Test patch: