AnimeshShaw commited on
Commit
ec03ecf
·
1 Parent(s): 5e4e5af

Add human_reference_dataset/iac-eval

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. human_reference_dataset/aws-cloudformation-templates +0 -1
  2. human_reference_dataset/iac-eval +0 -1
  3. human_reference_dataset/iac-eval/.gitignore +20 -0
  4. human_reference_dataset/iac-eval/LICENSE.txt +21 -0
  5. human_reference_dataset/iac-eval/README.md +55 -0
  6. human_reference_dataset/iac-eval/environment.yml +246 -0
  7. human_reference_dataset/iac-eval/evaluation/README.md +97 -0
  8. human_reference_dataset/iac-eval/evaluation/config.json +4 -0
  9. human_reference_dataset/iac-eval/evaluation/data.py +19 -0
  10. human_reference_dataset/iac-eval/evaluation/eval.py +1000 -0
  11. human_reference_dataset/iac-eval/evaluation/llm-judge-eval.py +263 -0
  12. human_reference_dataset/iac-eval/evaluation/logs/README.md +1 -0
  13. human_reference_dataset/iac-eval/evaluation/metrics.py +213 -0
  14. human_reference_dataset/iac-eval/evaluation/misc/ablation-judge/ablation-llm-judge.py +604 -0
  15. human_reference_dataset/iac-eval/evaluation/misc/ablation-multiple-sample/ablation-multiple-sample.py +731 -0
  16. human_reference_dataset/iac-eval/evaluation/misc/ablation/ablation-iac-eval-pipeline.py +667 -0
  17. human_reference_dataset/iac-eval/evaluation/misc/complete-dataset-measurement/complete-dataset-measurement.py +606 -0
  18. human_reference_dataset/iac-eval/evaluation/misc/sagemaker_setup/sagemaker-magicoder-s-cl-7b-deploy.py +90 -0
  19. human_reference_dataset/iac-eval/evaluation/models.py +338 -0
  20. human_reference_dataset/iac-eval/evaluation/prompt-templates/CoT.txt +66 -0
  21. human_reference_dataset/iac-eval/evaluation/prompt-templates/few-shot.txt +66 -0
  22. human_reference_dataset/iac-eval/evaluation/prompt-templates/multi-turn-system-prompt.txt +1 -0
  23. human_reference_dataset/iac-eval/evaluation/prompt-templates/system-prompt.txt +1 -0
  24. human_reference_dataset/iac-eval/evaluation/prompt_templates.py +56 -0
  25. human_reference_dataset/iac-eval/evaluation/setup.sh +3 -0
  26. human_reference_dataset/iac-eval/licenses/README.md +6 -0
  27. human_reference_dataset/iac-eval/retriever/README.md +27 -0
  28. human_reference_dataset/iac-eval/retriever/llama_index_retriever.py +108 -0
  29. human_reference_dataset/iac-eval/retriever/setup.sh +21 -0
  30. human_reference_dataset/iac-eval/setup.sh +29 -0
  31. human_reference_dataset/iac-eval/templates/aws_chime_voice_connector/main.tf +8 -0
  32. human_reference_dataset/iac-eval/templates/aws_chime_voice_connector/template.rego +21 -0
  33. human_reference_dataset/iac-eval/templates/aws_chime_voice_connector/tfplan.json +108 -0
  34. human_reference_dataset/iac-eval/templates/aws_iam_policy/main.tf +20 -0
  35. human_reference_dataset/iac-eval/templates/aws_iam_policy/template.rego +30 -0
  36. human_reference_dataset/iac-eval/templates/aws_iam_policy/tfplan.json +94 -0
  37. human_reference_dataset/iac-eval/templates/aws_iam_role/main.tf +28 -0
  38. human_reference_dataset/iac-eval/templates/aws_iam_role/template.rego +0 -0
  39. human_reference_dataset/iac-eval/templates/aws_iam_role/tfplan.json +131 -0
  40. human_reference_dataset/iac-eval/templates/aws_iam_user/main.tf +9 -0
  41. human_reference_dataset/iac-eval/templates/aws_iam_user/template.rego +28 -0
  42. human_reference_dataset/iac-eval/templates/aws_iam_user/tfplan.json +110 -0
  43. human_reference_dataset/iac-eval/templates/aws_lb/template.rego +147 -0
  44. human_reference_dataset/iac-eval/templates/aws_neptune_cluster/main.tf +70 -0
  45. human_reference_dataset/iac-eval/templates/aws_neptune_cluster/template.rego +68 -0
  46. human_reference_dataset/iac-eval/templates/aws_neptune_cluster/tfplan.json +749 -0
  47. human_reference_dataset/iac-eval/templates/aws_redshift_cluster/sns-event/main.tf +55 -0
  48. human_reference_dataset/iac-eval/templates/aws_redshift_cluster/sns-event/tfplan.json +577 -0
  49. human_reference_dataset/iac-eval/templates/aws_redshift_cluster/subnet-group/main.tf +48 -0
  50. human_reference_dataset/iac-eval/templates/aws_redshift_cluster/subnet-group/tfplan.json +675 -0
human_reference_dataset/aws-cloudformation-templates DELETED
@@ -1 +0,0 @@
1
- Subproject commit a0f43bc6d20813052892546f445037cf84c75b54
 
 
human_reference_dataset/iac-eval DELETED
@@ -1 +0,0 @@
1
- Subproject commit b75a90b32a9733b17b12cf82535121793cb228e5
 
 
human_reference_dataset/iac-eval/.gitignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.hcl
2
+ .terraform
3
+ *.tfstate
4
+ *.tfstate.backup
5
+ *.binary
6
+ .DS_Store
7
+ data/**/*
8
+ */.DS_Store
9
+ *.env
10
+ evaluation/terraform_config/.terraform
11
+ */__pycache__/
12
+ retriever/aws-index/
13
+ retriever/terraform-provider-aws/
14
+ .vscode/
15
+ evaluation/tmp/rego_config/**/*
16
+ evaluation/tmp/terraform_config/**/*
17
+ evaluation/tmp/*
18
+ evaluation/misc/complete-dataset-measurement/terraform_config/*
19
+ evaluation/misc/complete-dataset-measurement/rego_config/*
20
+ evaluation/misc/ablation/terraform_config/*
human_reference_dataset/iac-eval/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 autoiac-project
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
human_reference_dataset/iac-eval/README.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">| <a href="https://huggingface.co/datasets/autoiac-project/iac-eval"><u>Dataset</u></a> | 🏆 <a href="https://huggingface.co/datasets/autoiac-project/iac-eval"><u>Leaderboard TBD</u></a> | 📖 <a href="https://www.cs-pk.com/neurips24-iac-eval.pdf"><u>NeurIPS 2024 Paper</u></a> |</p>
2
+
3
+ # IaC-Eval---first edition
4
+
5
+ IaC-Eval is a comprehensive framework for quantitatively evaluating the capabilities of large language models in cloud IaC code generation. Infrastructure-as-Code (IaC) is an important component of cloud computing, that allows the definition of cloud infrastructure in high-level programs. Our framework targets Terraform specifically for now. We leave integration of other IaC tools as future work.
6
+
7
+ IaC-Eval also provides the first human-curated and challenging Infrastructure-as-Code (IaC) dataset containing 458 questions ranging from simple to difficult across various cloud services (targeting AWS for now), which can be found in our [HuggingFace repository](https://huggingface.co/datasets/autoiac-project/iac-eval).
8
+
9
+ **We are actively developing and patching the project. However, as of now, IaC-Eval is not production-ready.**
10
+
11
+ ## Installation
12
+
13
+ 1. Install Terraform (also [install AWS CLI and setup credentials](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-build#prerequisites))
14
+ 2. Install [Opa](https://www.openpolicyagent.org/docs/latest/#1-download-opa) (make sure to add opa to path).
15
+ 3. <sup>*</sup>Obtain the following LLM model inference API keys as appropriate, depending on which of our currently supported models you want to perform evaluation on:
16
+ - [OpenAI API token](https://platform.openai.com/docs/quickstart/account-setup): for GPT-3.5-Turbo and GPT-4
17
+ - [Google API token](https://ai.google.dev/gemini-api/docs/quickstart?lang=python#set-up-api-key): for Gemini-1.0-Pro
18
+ - [Replicate API token](https://replicate.com/): for CodeLlama and WizardCoder variants
19
+
20
+ <sup>*</sup> Our evaluation against MagiCoder was performed on a manually deployed AWS SageMaker instance inference endpoint. We provide more details on our setup script, see `evaluation/README.md`, if that is of interest.
21
+
22
+ ### Using the Evaluation Pipeline
23
+
24
+ To access and utilize the evaluation pipeline, you need to switch to a specific branch of this repository and set up the environment. Follow these steps:
25
+
26
+ 1. Ensure you have the `main` branch of the project checked out.
27
+
28
+ 2. Install the Conda environment by running:
29
+
30
+ ```shell
31
+ conda env create -f environment.yml
32
+ ```
33
+
34
+ 3. Activate the newly created Conda environment named `iac-eval`:
35
+
36
+ ```shell
37
+ conda activate iac-eval
38
+ ```
39
+
40
+ Note: before `conda activate` you might need to do `conda init SHELL_NAME` on your preferred shell (e.g. `conda init bash`). If you run into problems initializing the shell session, try referring to [this GitHub issue](https://github.com/conda/conda/issues/13423#issuecomment-2113968807) for a fix.
41
+
42
+ 4. (Optional) Preconfigure the retriever database (if you would like to use the RAG strategy): refer to instructions in `retriever/README.md`.
43
+
44
+ 5. See instructions in `evaluation/README.md` for details on how to use the main pipeline: `eval.py`, and other scripts.
45
+
46
+ Note: You can run `./setup.sh` to check if you have Terraform and OPA installed. It will also create and activate the necessary conda environment. The shell script assumes you are using `bash`, change `#!/bin/SHELL` to your preferred shell in the script.
47
+
48
+ ## Contributing
49
+
50
+ We welcome all forms of contribution! IaC-Eval aims to quantitatively and comprehensively evaluate the IaC code generation capabilities of large language models. If you find bugs or have ideas, please share them via GitHub Issues. This includes contributions to IaC-Eval's dataset, whose format can be found in it's [HuggingFace repository](https://huggingface.co/datasets/autoiac-project/iac-eval).
51
+
52
+
53
+ ## Acknowledgments
54
+
55
+ <https://github.com/openai/human-eval/tree/master>
human_reference_dataset/iac-eval/environment.yml ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: iac-eval
2
+ channels:
3
+ - defaults
4
+ dependencies:
5
+ - _libgcc_mutex=0.1=main
6
+ - _openmp_mutex=5.1=1_gnu
7
+ - bzip2=1.0.8=h5eee18b_5
8
+ - ca-certificates=2024.3.11=h06a4308_0
9
+ - ld_impl_linux-64=2.38=h1181459_1
10
+ - libffi=3.4.4=h6a678d5_0
11
+ - libgcc-ng=11.2.0=h1234567_1
12
+ - libgomp=11.2.0=h1234567_1
13
+ - libstdcxx-ng=11.2.0=h1234567_1
14
+ - libuuid=1.41.5=h5eee18b_0
15
+ - ncurses=6.4=h6a678d5_0
16
+ - openssl=3.0.13=h7f8727e_0
17
+ - pip=23.3.1=py310h06a4308_0
18
+ - python=3.10.14=h955ad1f_0
19
+ - readline=8.2=h5eee18b_0
20
+ - setuptools=68.2.2=py310h06a4308_0
21
+ - sqlite=3.41.2=h5eee18b_0
22
+ - tk=8.6.12=h1ccaba5_0
23
+ - wheel=0.41.2=py310h06a4308_0
24
+ - xz=5.4.6=h5eee18b_0
25
+ - zlib=1.2.13=h5eee18b_0
26
+ - pip:
27
+ - aiohttp==3.9.5
28
+ - aiosignal==1.3.1
29
+ - annotated-types==0.6.0
30
+ - anyio==4.3.0
31
+ - asgiref==3.8.1
32
+ - async-timeout==4.0.3
33
+ - attrs==23.2.0
34
+ - azure-core==1.30.1
35
+ - azure-identity==1.16.0
36
+ - backoff==2.2.1
37
+ - bcrypt==4.1.3
38
+ - beautifulsoup4==4.12.3
39
+ - boto3==1.34.98
40
+ - botocore==1.34.98
41
+ - build==1.2.1
42
+ - cachetools==5.3.3
43
+ - certifi==2024.2.2
44
+ - cffi==1.16.0
45
+ - charset-normalizer==3.3.2
46
+ - chroma-hnswlib==0.7.3
47
+ - chromadb==0.4.24
48
+ - click==8.1.7
49
+ - cloudpickle==2.2.1
50
+ - code-bert-score==0.4.1
51
+ - coloredlogs==15.0.1
52
+ - contourpy==1.2.0
53
+ - cryptography==42.0.7
54
+ - cycler==0.12.1
55
+ - dataclasses-json==0.6.6
56
+ - datasets==2.19.2
57
+ - deprecated==1.2.14
58
+ - dill==0.3.8
59
+ - dirtyjson==1.0.8
60
+ - distro==1.9.0
61
+ - dnspython==2.6.1
62
+ - docker==7.0.0
63
+ - email-validator==2.1.1
64
+ - exceptiongroup==1.2.1
65
+ - fastapi==0.111.0
66
+ - fastapi-cli==0.0.3
67
+ - filelock==3.14.0
68
+ - flatbuffers==24.3.25
69
+ - fonttools==4.50.0
70
+ - frozenlist==1.4.1
71
+ - fsspec==2024.3.1
72
+ - google-ai-generativelanguage==0.6.2
73
+ - google-api-core==2.18.0
74
+ - google-api-python-client==2.127.0
75
+ - google-auth==2.29.0
76
+ - google-auth-httplib2==0.2.0
77
+ - google-generativeai==0.5.2
78
+ - google-pasta==0.2.0
79
+ - googleapis-common-protos==1.63.0
80
+ - greenlet==3.0.3
81
+ - grpcio==1.62.2
82
+ - grpcio-status==1.62.2
83
+ - h11==0.14.0
84
+ - httpcore==1.0.5
85
+ - httplib2==0.22.0
86
+ - httptools==0.6.1
87
+ - httpx==0.27.0
88
+ - huggingface-hub==0.23.0
89
+ - humanfriendly==10.0
90
+ - idna==3.6
91
+ - importlib-metadata==6.11.0
92
+ - importlib-resources==6.4.0
93
+ - jinja2==3.1.4
94
+ - jmespath==1.0.1
95
+ - joblib==1.4.2
96
+ - jsonpatch==1.33
97
+ - jsonpointer==2.4
98
+ - jsonschema==4.22.0
99
+ - jsonschema-specifications==2023.12.1
100
+ - kiwisolver==1.4.5
101
+ - kubernetes==29.0.0
102
+ - langchain==0.1.13
103
+ - langchain-community==0.0.38
104
+ - langchain-core==0.1.52
105
+ - langchain-openai==0.1.1
106
+ - langchain-text-splitters==0.0.1
107
+ - langsmith==0.1.57
108
+ - llama-index==0.10.34
109
+ - llama-index-agent-openai==0.2.3
110
+ - llama-index-cli==0.1.12
111
+ - llama-index-core==0.10.34
112
+ - llama-index-embeddings-azure-openai==0.1.9
113
+ - llama-index-embeddings-openai==0.1.9
114
+ - llama-index-indices-managed-llama-cloud==0.1.6
115
+ - llama-index-legacy==0.9.48
116
+ - llama-index-llms-azure-openai==0.1.7
117
+ - llama-index-llms-openai==0.1.16
118
+ - llama-index-multi-modal-llms-openai==0.1.5
119
+ - llama-index-program-openai==0.1.6
120
+ - llama-index-question-gen-openai==0.1.3
121
+ - llama-index-readers-file==0.1.20
122
+ - llama-index-readers-llama-parse==0.1.4
123
+ - llama-parse==0.4.2
124
+ - llamaindex-py-client==0.1.19
125
+ - markdown-it-py==3.0.0
126
+ - markupsafe==2.1.5
127
+ - marshmallow==3.21.2
128
+ - matplotlib==3.8.3
129
+ - mdurl==0.1.2
130
+ - mmh3==4.1.0
131
+ - monotonic==1.6
132
+ - mpmath==1.3.0
133
+ - msal==1.28.0
134
+ - msal-extensions==1.1.0
135
+ - multidict==6.0.5
136
+ - multiprocess==0.70.16
137
+ - mypy-extensions==1.0.0
138
+ - nest-asyncio==1.6.0
139
+ - networkx==3.3
140
+ - nltk==3.8.1
141
+ - numpy==1.26.4
142
+ - nvidia-cublas-cu12==12.1.3.1
143
+ - nvidia-cuda-cupti-cu12==12.1.105
144
+ - nvidia-cuda-nvrtc-cu12==12.1.105
145
+ - nvidia-cuda-runtime-cu12==12.1.105
146
+ - nvidia-cudnn-cu12==8.9.2.26
147
+ - nvidia-cufft-cu12==11.0.2.54
148
+ - nvidia-curand-cu12==10.3.2.106
149
+ - nvidia-cusolver-cu12==11.4.5.107
150
+ - nvidia-cusparse-cu12==12.1.0.106
151
+ - nvidia-nccl-cu12==2.20.5
152
+ - nvidia-nvjitlink-cu12==12.5.40
153
+ - nvidia-nvtx-cu12==12.1.105
154
+ - oauthlib==3.2.2
155
+ - onnxruntime==1.17.3
156
+ - openai==1.14.2
157
+ - opentelemetry-api==1.24.0
158
+ - opentelemetry-exporter-otlp-proto-common==1.24.0
159
+ - opentelemetry-exporter-otlp-proto-grpc==1.24.0
160
+ - opentelemetry-instrumentation==0.45b0
161
+ - opentelemetry-instrumentation-asgi==0.45b0
162
+ - opentelemetry-instrumentation-fastapi==0.45b0
163
+ - opentelemetry-proto==1.24.0
164
+ - opentelemetry-sdk==1.24.0
165
+ - opentelemetry-semantic-conventions==0.45b0
166
+ - opentelemetry-util-http==0.45b0
167
+ - orjson==3.10.3
168
+ - overrides==7.7.0
169
+ - packaging==23.2
170
+ - pandas==2.2.1
171
+ - pathos==0.3.2
172
+ - pillow==10.3.0
173
+ - platformdirs==4.2.1
174
+ - portalocker==2.8.2
175
+ - posthog==3.5.0
176
+ - pox==0.3.4
177
+ - ppft==1.7.6.8
178
+ - proto-plus==1.23.0
179
+ - protobuf==4.25.3
180
+ - psutil==5.9.8
181
+ - pulsar-client==3.5.0
182
+ - pyarrow==16.1.0
183
+ - pyarrow-hotfix==0.6
184
+ - pyasn1==0.5.1
185
+ - pyasn1-modules==0.3.0
186
+ - pycparser==2.22
187
+ - pydantic==2.7.1
188
+ - pydantic-core==2.18.2
189
+ - pygments==2.18.0
190
+ - pyjwt==2.8.0
191
+ - pyparsing==3.1.2
192
+ - pypdf==4.2.0
193
+ - pypika==0.48.9
194
+ - pyproject-hooks==1.1.0
195
+ - python-dateutil==2.9.0.post0
196
+ - python-dotenv==1.0.1
197
+ - python-multipart==0.0.9
198
+ - pytz==2024.1
199
+ - pyyaml==6.0.1
200
+ - referencing==0.35.1
201
+ - regex==2024.5.10
202
+ - replicate==0.25.1
203
+ - requests==2.32.3
204
+ - requests-oauthlib==2.0.0
205
+ - rich==13.7.1
206
+ - rpds-py==0.18.0
207
+ - rsa==4.9
208
+ - s3transfer==0.10.1
209
+ - safetensors==0.4.3
210
+ - sagemaker==2.218.1
211
+ - schema==0.7.7
212
+ - shellingham==1.5.4
213
+ - six==1.16.0
214
+ - smdebug-rulesconfig==1.0.1
215
+ - sniffio==1.3.1
216
+ - soupsieve==2.5
217
+ - sqlalchemy==2.0.30
218
+ - starlette==0.37.2
219
+ - striprtf==0.0.26
220
+ - sympy==1.12
221
+ - tblib==3.0.0
222
+ - tenacity==8.3.0
223
+ - tiktoken==0.6.0
224
+ - tokenizers==0.19.1
225
+ - tomli==2.0.1
226
+ - torch==2.3.0
227
+ - tqdm==4.66.4
228
+ - transformers==4.41.2
229
+ - triton==2.3.0
230
+ - typer==0.12.3
231
+ - typing-extensions==4.11.0
232
+ - typing-inspect==0.9.0
233
+ - tzdata==2024.1
234
+ - ujson==5.9.0
235
+ - uritemplate==4.1.1
236
+ - urllib3==2.2.1
237
+ - uvicorn==0.29.0
238
+ - uvloop==0.19.0
239
+ - watchfiles==0.21.0
240
+ - websocket-client==1.8.0
241
+ - websockets==12.0
242
+ - wrapt==1.16.0
243
+ - xxhash==3.4.1
244
+ - yarl==1.9.4
245
+ - zipp==3.18.1
246
+ prefix: /home/ubuntu/miniconda3/envs/iac-eval
human_reference_dataset/iac-eval/evaluation/README.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation Setup
2
+
3
+ ## Usage guide
4
+
5
+ All commands assume you are in the `evaluation` directory, and that you have activated the env:
6
+
7
+ ```bash
8
+ conda activate iac-eval
9
+ ```
10
+
11
+ Note: You can run `./setup.sh` for dependency check/setup.
12
+
13
+ Please run the following scripts in order. Note that the main evaluation pipeline will generate the base results, that will be used by the other scripts (except for "Complete dataset measurements") to calculate certain metrics (e.g., Pass@K or LLM-judge).
14
+
15
+ ### Main evaluation pipeline
16
+
17
+ #### 🚀 Quick Start Demo Run
18
+
19
+ The following will default to a sample size of 1 per task, and perform the evaluation for WizardCoder33B (via Replicate) only, but only for a subset (2 rows) of our main dataset. Useful for testing the functionality of the benchmark.
20
+
21
+ ```bash
22
+ python3 eval.py --config=config.json --quick-test
23
+ ```
24
+
25
+ #### 🔥 Quick Start
26
+
27
+ The following will default to a sample size of 1 per task, and perform the evaluation for WizardCoder33B (via Replicate) only. This will perform the evaluation on all rows in the dataset, which can take a significant amount of time.
28
+
29
+ ```bash
30
+ python3 eval.py --config=config.json
31
+ ```
32
+
33
+ #### Instructions
34
+
35
+ This function takes in data from the `data/` folder, and the evaluation results are written to the respective model folders (e.g., `/tmp/gpt4/` stores the temporary evaluated results, while `/results/gpt4` stores the final results).
36
+
37
+ Options for prompt-enhancement-strategy: COT, FSP, RAG, multi-turn
38
+
39
+ Specify the number of samples per task and evaluation models list using command line options (`python3 eval.py --help` for help) or config file with `python3 eval.py --config=PATH_TO_FILE` to your desired value, and run the evaluation pipeline using:
40
+
41
+ ```bash
42
+ python3 eval.py [command-options]
43
+ ```
44
+
45
+ <!-- 💡 -->
46
+
47
+ > :exclamation: **Note**
48
+ > 1. If no other values are specified, the evaluation is defaulted to run on all models in the models list with a sample size of 20 per task.
49
+ > 2. If the script unexpectedly stops (e.g., due to an unforeseen error), you can directly rerun the script. It will continue where it left off.
50
+
51
+ ### LLM judge pipeline
52
+
53
+ This currently only applies the GPT4-single LLM-judge metric onto the evaluated datasets. Outputs in `../results/<model>/llm-judge-evaluation-metric/`
54
+
55
+ ```bash
56
+ python3 llm-judge-eval.py gpt4 llm-single
57
+ ```
58
+
59
+ #### Complete dataset measurements:
60
+ This script outputs a few json files which give us the difficulty level and resource distributions.
61
+ This script also reads from `data/` and outputs the same dataset but with filled in "Difficulty" and "Resource" values, in `misc/complete-dataset-measurement/complete-dataset`.
62
+ ```bash
63
+ python3 misc/complete-dataset-measurement/complete-dataset-measurement.py
64
+ ```
65
+
66
+ ### Ablation calculation
67
+ This script mainly calculates other metrics such as BLEU, score by difficulty, accuracy, etc.
68
+ This reads from `data`, and `evaluation/results` and outputs an `input_composition_dict.json` that gives the files that will be processed, and also incrementally outputs an `output_composition_dict.json` that contains the results.
69
+
70
+ This script assumes that the "Difficulty" and "Resource" columns of the dataset CSV file are properly filled; if this is not the case (e.g., new version of the dataset), please run the above script once, and move the resulting dataset CSV file manually to the `data` directory.
71
+
72
+ ```bash
73
+ python3 misc/ablation/ablation-iac-eval-pipeline.py
74
+ ```
75
+
76
+ #### Ablation LLM-judge related calculation:
77
+ This script calculates LLM judge metrics given results from LLM judge in `../results/<model>/llm-judge-evaluation-metric/`.
78
+ This reads from `../results/<model>/llm-judge-evaluation-metric/`, and outputs an `input_composition_dict.json` that gives the files that will be processed, and also incrementally outputs an `output_composition_dict.json` that contains the results.
79
+ ```bash
80
+ python3 misc/ablation-judge/ablation-llm-judge.py
81
+ ```
82
+
83
+ #### Ablation Pass@k related calculation:
84
+ This script calculates Pass@k metrics given results in `../results`.
85
+ This reads from `../results/`, and outputs an `input_composition_dict.json` that gives the files that will be processed, and also incrementally outputs an `pass-k-output_composition_dict.json` that contains the results.
86
+
87
+ Make sure that the value of the command line option `n` is set to below or equal to the number of evaluation samples that exist in `../results`, e.g., if GPT-4 had 2 generated samples, then `n<=2`.
88
+ ```bash
89
+ python3 misc/ablation-multiple-sample/ablation-multiple-sample.py -n 20 # N refers to the number of samples.
90
+ ```
91
+
92
+ ### Sagemaker usage (for MagiCoder-S-CL-7B evaluation)
93
+ This deploys a AWS SageMaker instance inference model and endpoint, running MagiCoder-S-CL-7B, that we can then later call for evaluation.
94
+
95
+ ```bash
96
+ python3 misc/sagemaker_setup/sagemaker-magicoder-s-cl-7b-deploy.py
97
+ ```
human_reference_dataset/iac-eval/evaluation/config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "samples": 1,
3
+ "models": ["Wizardcoder33b"]
4
+ }
human_reference_dataset/iac-eval/evaluation/data.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ import pandas as pd
3
+ import os
4
+
5
+ def import_dataset(quick_test=False):
6
+ # Load the entire dataset
7
+ if not quick_test:
8
+ dataset = load_dataset("autoiac-project/iac-eval", split="test")
9
+ else:
10
+ dataset = load_dataset("autoiac-project/iac-eval", "quick_test", split="test")
11
+
12
+ # convert the entire dataset to a Pandas DataFrame
13
+ df = dataset.to_pandas()
14
+
15
+ # Create directory if not exists:
16
+ os.makedirs("../data/complete", exist_ok=True)
17
+
18
+ # Save the dataset to a CSV file
19
+ df.to_csv("../data/complete/data.csv", index=False)
human_reference_dataset/iac-eval/evaluation/eval.py ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import csv
4
+ import sys
5
+ from pathlib import Path
6
+ from openai import OpenAI
7
+ import numpy as np
8
+ import pandas as pd
9
+ import subprocess
10
+ import json
11
+ import getpass
12
+ import uuid
13
+ import re
14
+ import time
15
+ import logging
16
+ import models
17
+ import prompt_templates
18
+ import data
19
+ import math
20
+
21
+ sys.path.append(
22
+ os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "retriever"))
23
+ )
24
+ import llama_index_retriever
25
+ import click
26
+ from typing import List, Tuple
27
+
28
+ DEFAULT_LOG_FILE = "logs/eval.log"
29
+ DELIMITERS = ["```hcl", "```json", "```HCL", "```Terraform", "```terraform", "```"]
30
+ # ``` needs to be in the end, as it is a final "else" case
31
+
32
+ # Default configurations if not specified
33
+ NUM_SAMPLES_PER_TASK = 20 # n
34
+ EVAL_MODELS = [
35
+ "gpt3.5",
36
+ "gpt4",
37
+ "gemini-1.0-pro",
38
+ "codellama-7b",
39
+ "codellama-13b",
40
+ "codellama-34b",
41
+ "Magicoder_S_CL_7B",
42
+ "Wizardcoder33b",
43
+ "Wizardcoder34b",
44
+ ] # default to all available models
45
+
46
+ PROMPT_ENHANCEMENT_STRATS = ["RAG", "COT", "FSP", "multi-turn", ""]
47
+
48
+ class CustomFormatter(logging.Formatter):
49
+ # https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
50
+ grey = "\x1b[38;20m"
51
+ cyan = "\x1b[36;20m"
52
+ blue = "\x1b[34:20m"
53
+ yellow = "\x1b[33;20m"
54
+ red = "\x1b[31;20m"
55
+ bold_red = "\x1b[31;1m"
56
+ reset = "\x1b[0m"
57
+ format = (
58
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
59
+ )
60
+
61
+ FORMATS = {
62
+ logging.DEBUG: cyan + format + reset,
63
+ logging.INFO: blue + format + reset,
64
+ logging.WARNING: yellow + format + reset,
65
+ logging.ERROR: red + format + reset,
66
+ logging.CRITICAL: bold_red + format + reset,
67
+ }
68
+
69
+ def format(self, record):
70
+ log_fmt = self.FORMATS.get(record.levelno)
71
+ formatter = logging.Formatter(log_fmt)
72
+ return formatter.format(record)
73
+
74
+
75
+ logger = logging.getLogger("iac-eval") # get logger
76
+
77
+
78
+ # https://stackoverflow.com/questions/12507206/how-to-completely-traverse-a-complex-dictionary-of-unknown-depth
79
+ def dict_generator(indict, pre=None):
80
+ pre = pre[:] if pre else []
81
+ if isinstance(indict, dict):
82
+ for key, value in indict.items():
83
+ if isinstance(value, dict):
84
+ for d in dict_generator(value, pre + [key]):
85
+ yield d
86
+ elif isinstance(value, list) or isinstance(value, tuple):
87
+ for v in value:
88
+ for d in dict_generator(v, pre + [key]):
89
+ yield d
90
+ else:
91
+ yield pre + [key, value]
92
+ else:
93
+ yield pre + [indict]
94
+
95
+
96
+ def rag_knowledge(Retriever, query):
97
+ knowledge = ""
98
+ questions = Retriever.generate_prompt_for_index(query)
99
+ context = Retriever.query_documents(questions)
100
+ for i, c in enumerate(context):
101
+ if i >= 4:
102
+ break
103
+ knowledge += f"Context {i}: \n"
104
+ knowledge += c
105
+ return knowledge
106
+
107
+
108
+ # remove unwanted text for output
109
+ def remove_unwanted_characters(text):
110
+ if text is None:
111
+ return None
112
+
113
+ ansi_escape = re.compile(r"\x1B[@-_][0-?]*[ -/]*[@-~]")
114
+ text = ansi_escape.sub("", text)
115
+ unwanted_pattern = re.compile(r"[^\x00-\x7F]+") # Non-ASCII characters
116
+ text = unwanted_pattern.sub("", text)
117
+
118
+ return text
119
+
120
+
121
+ def delete_all_files_in_directory(folder):
122
+ if not os.path.isdir(folder):
123
+ return
124
+ for filename in os.listdir(folder):
125
+ file_path = os.path.join(folder, filename)
126
+ try:
127
+ if os.path.isfile(file_path) or os.path.islink(file_path):
128
+ os.unlink(file_path)
129
+ elif os.path.isdir(file_path):
130
+ shutil.rmtree(file_path)
131
+ except Exception as e:
132
+ print("Failed to delete %s. Reason: %s" % (file_path, e))
133
+
134
+
135
+ # setup aws credential
136
+ def set_aws_credentials():
137
+ # prompt the user for AWS credentials
138
+ # set the credentials as environment variables
139
+ if "AWS_ACCESS_KEY_ID" not in os.environ:
140
+ aws_access_key_id = input("Enter AWS Access Key ID: ")
141
+ os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id
142
+ if "AWS_SECRET_ACCESS_KEY" not in os.environ:
143
+ aws_secret_access_key = getpass.getpass("Enter AWS Secret Access Key: ")
144
+ os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key
145
+ if "AWS_ROLE_NAME" not in os.environ:
146
+ aws_role_name = input("Enter AWS Role Name to be used (press Enter to use the default value 'default'): " or "default")
147
+ os.environ["AWS_ROLE_NAME"] = aws_role_name
148
+
149
+ def set_google_credentials():
150
+ # For gemini:
151
+ if "GOOGLE_API_KEY" not in os.environ:
152
+ gemini_secret_access_key = getpass.getpass(
153
+ "Enter Google API Key (for Gemini): "
154
+ )
155
+ os.environ["GOOGLE_API_KEY"] = gemini_secret_access_key
156
+
157
+
158
+ def set_replicate_credentials():
159
+ # For Replicate:
160
+ if "REPLICATE_API_TOKEN" not in os.environ:
161
+ replicate_secret_access_key = getpass.getpass(
162
+ "Enter Replicate API Key (for various models): "
163
+ )
164
+ os.environ["REPLICATE_API_TOKEN"] = replicate_secret_access_key
165
+
166
+
167
+ def set_huggingface_credentials():
168
+ # For gemini:
169
+ if "HF_API_TOKEN" not in os.environ:
170
+ hf_secret_access_key = getpass.getpass(
171
+ "Enter Huggingface API Token (for use of various models): "
172
+ )
173
+ os.environ["HF_API_TOKEN"] = hf_secret_access_key
174
+
175
+
176
+ # split the code for results
177
+ def separate_answer_and_code(text, delimiters=["```hcl"]):
178
+ for delimiter in delimiters:
179
+ # split the text at the point where the code block starts
180
+ parts = text.split(delimiter)
181
+ # print(len(parts))
182
+ if len(parts) < 2:
183
+ # delimiter not found, return original text and empty code
184
+ answer = text.strip()
185
+ code = ""
186
+ continue
187
+ # the first part is the answer
188
+ answer = parts[0].strip()
189
+ # the second part is the code, re-adding the "```hcl" and removing the trailing "```"
190
+ code = parts[1].strip()
191
+ code = code.rsplit("```", 1)[0].strip()
192
+ if code != "":
193
+ return answer, code
194
+ return answer, code
195
+
196
+
197
+ # find each subdirectory
198
+ def list_all_subdirectories_and_eval(
199
+ data_dir, base_eval_dir, final_eval_dir, PROMPT_ENHANCEMENT_STRAT, Retriever
200
+ ):
201
+ for path, _, _ in os.walk(data_dir):
202
+ subdir = path.removeprefix(
203
+ data_dir + "/"
204
+ ) # FIX?: temp fix for now, the way to go is prob using pathlib
205
+ create_evaluation_directories(subdir, base_eval_dir=base_eval_dir, final_eval_dir=final_eval_dir)
206
+ file_dir = os.listdir(path)
207
+ for file in file_dir:
208
+ if file.endswith(".csv"):
209
+ file_path = os.path.abspath(os.path.join(path, file))
210
+ print(file_path)
211
+ # Perform evaluation:
212
+ for model in EVAL_MODELS:
213
+ # Note: Do not overwrite existing files, and do not evaluate if file exists already
214
+ eval_filepath, final_file_path, file_exists, NUM_EXISTING_SAMPLES = (
215
+ copy_csv_to_evaluation(
216
+ file_path,
217
+ subdir,
218
+ model,
219
+ PROMPT_ENHANCEMENT_STRAT,
220
+ base_eval_dir=base_eval_dir,
221
+ final_eval_dir=final_eval_dir,
222
+ )
223
+ )
224
+ if file_exists:
225
+ continue
226
+ read_models(
227
+ model,
228
+ PROMPT_ENHANCEMENT_STRAT,
229
+ NUM_EXISTING_SAMPLES,
230
+ eval_filepath,
231
+ final_file_path,
232
+ Retriever,
233
+ )
234
+
235
+
236
+ # function to create evaluation directories based on a given subdirectory
237
+ def create_evaluation_directories(subdir, base_eval_dir="evaluation/tmp", final_eval_dir="results"):
238
+ for model in EVAL_MODELS:
239
+ # construct the new directory path
240
+ eval_dir_path = os.path.join(base_eval_dir, model, subdir)
241
+ final_eval_dir_path = os.path.join(final_eval_dir, model, subdir)
242
+ # create the directory if it does not exist
243
+ os.makedirs(eval_dir_path, exist_ok=True)
244
+ os.makedirs(final_eval_dir_path, exist_ok=True)
245
+
246
+
247
+ def make_column_names_unique(df):
248
+ cols = pd.Series(df.columns)
249
+ for dup in cols[cols.duplicated()].unique():
250
+ cols[cols[cols == dup].index.values.tolist()] = [
251
+ dup + "." + str(i) if i != 0 else dup for i in range(sum(cols == dup))
252
+ ]
253
+ df.columns = cols
254
+ # print(cols.tolist())
255
+ # while True:
256
+ # x=1
257
+ return df
258
+
259
+
260
+ def fix_duplicate_columns(dest_file_path):
261
+ """
262
+ Deduplicated csv is written to original file path
263
+ """
264
+ # FIX?: this is ignoring the header in the original file and manually extracting the first line???
265
+ df = pd.read_csv(dest_file_path, header=None)
266
+ new_header = df.iloc[0]
267
+ df = df[1:]
268
+ df.columns = new_header
269
+ df.reset_index(drop=True, inplace=True)
270
+
271
+ if not df.columns.is_unique: # First check if there are duplicate columns:
272
+ df = make_column_names_unique(df)
273
+ df.to_csv(dest_file_path, index=False, encoding="utf-8")
274
+ logger.info(
275
+ f"Evaluation file {dest_file_path} had duplicate columns, deduplicated them."
276
+ )
277
+
278
+
279
+ def determine_eval_samples(dest_file_path):
280
+ """
281
+ Determine the number of samples currently present in a given evaluated dataset file.
282
+ Also determines columns to remove (i.e., which are empty, because a previous evaluation run was not complete, which can only occur if copy_csv was successful but read_models was interrupted)
283
+ Note: this is a variant of the same function used in llm-judge-eval.py
284
+ """
285
+
286
+ drop_cols = []
287
+
288
+ df = pd.read_csv(dest_file_path, header=None)
289
+ new_header = df.iloc[0]
290
+ df = df[1:]
291
+ df.columns = new_header
292
+ df.reset_index(drop=True, inplace=True)
293
+
294
+ num_samples = 0
295
+ for col in df.columns:
296
+ if "LLM Correct?" in col:
297
+ if not pd.isnull(
298
+ df[col].iloc[0]
299
+ ): # this means that the column is not empty (i.e., prev evaluation passed through successfully)
300
+ num_samples += 1
301
+ else:
302
+ cols_to_drop = [
303
+ "LLM Output #",
304
+ "LLM Plannable? #",
305
+ "LLM Correct? #",
306
+ "LLM Plan Phase Error #",
307
+ "LLM OPA match phase Error #",
308
+ "LLM Notes #",
309
+ ] # drop all columns for this sample
310
+ drop_cols.extend(
311
+ [col_base + str(col.split("#")[1]) for col_base in cols_to_drop]
312
+ )
313
+
314
+ return num_samples, drop_cols
315
+
316
+
317
+ # function to copy CSV to the new evaluation directory and rename it
318
+ def copy_csv_to_evaluation(
319
+ src_file_path,
320
+ subdir,
321
+ model,
322
+ PROMPT_ENHANCEMENT_STRAT,
323
+ base_eval_dir="evaluation/tmp",
324
+ final_eval_dir="results",
325
+ ):
326
+ # FIX?: this should be passed in as Path? if we are using Path, we should use it outside instead of os.
327
+ # dataset_file_name = os.path.basename(src_file_path)
328
+ dataset_file_name = Path(
329
+ src_file_path
330
+ ).stem # https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
331
+ eval_filename_prefix = "evaluation-dataset-for-{}".format(dataset_file_name)
332
+ # eval_filename = eval_file_name_prefix + "-" + dataset_file_name
333
+
334
+ eval_filename = (
335
+ "{}-{}.csv".format(eval_filename_prefix, PROMPT_ENHANCEMENT_STRAT)
336
+ if PROMPT_ENHANCEMENT_STRAT != ""
337
+ else "{}.csv".format(eval_filename_prefix)
338
+ )
339
+
340
+ dest_file_path = os.path.join(base_eval_dir, model, subdir, eval_filename)
341
+
342
+ final_file_path = os.path.join(final_eval_dir, model, subdir, eval_filename)
343
+
344
+ df = pd.read_csv(src_file_path, header=None)
345
+ # set the third row as the header
346
+ # FIX?: if this is the case for every file, why are they even saved?
347
+
348
+ new_header = df.iloc[0]
349
+ df = df[1:]
350
+ df.columns = new_header
351
+ # reset the index of the DataFrame
352
+ df.reset_index(drop=True, inplace=True)
353
+
354
+ num_eval_samples = 0 # current eval samples in the evaluated dataset file.
355
+
356
+ # Skip if file already exists and contains enough samples:
357
+ if os.path.isfile(dest_file_path):
358
+ fix_duplicate_columns(dest_file_path)
359
+ num_eval_samples, drop_cols = determine_eval_samples(dest_file_path)
360
+ if num_eval_samples >= NUM_SAMPLES_PER_TASK:
361
+ logger.info(
362
+ f"Skipping evaluation for {dest_file_path} as file already exists, and it has enough samples."
363
+ )
364
+ return dest_file_path, None, True, num_eval_samples
365
+
366
+ logger.info(
367
+ f"Evaluation file {dest_file_path} already exists, but has not enough samples (required: {NUM_SAMPLES_PER_TASK}, existing: {num_eval_samples}), will continue evaluation."
368
+ )
369
+ # Replace df with existing evaluated dataset file df:
370
+ # FIX?: this is ignoring the header in the original file and manually extracting the first line??? why?????
371
+ df = pd.read_csv(dest_file_path, header=None)
372
+ new_header = df.iloc[0]
373
+ df = df[1:]
374
+ df.columns = new_header
375
+ # reset the index of the DataFrame
376
+ df.reset_index(drop=True, inplace=True)
377
+
378
+ if len(drop_cols) > 0:
379
+ df.drop(columns=drop_cols, inplace=True)
380
+
381
+ logger.info(f"Performing evaluation on {dest_file_path}.")
382
+ # read the rest of the file starting from the fourth row without a header
383
+
384
+ # add new columns only to df
385
+ for i in range(num_eval_samples, NUM_SAMPLES_PER_TASK):
386
+ for col_base in [
387
+ "LLM Output #",
388
+ "LLM Plannable? #",
389
+ "LLM Correct? #",
390
+ "LLM Plan Phase Error #",
391
+ "LLM OPA match phase Error #",
392
+ "LLM Notes #",
393
+ ]:
394
+ df[col_base + str(i)] = ""
395
+
396
+ df.to_csv(dest_file_path, index=False, encoding="utf-8")
397
+
398
+ return dest_file_path, final_file_path, False, num_eval_samples
399
+
400
+
401
+ # gpt result
402
+ def read_models(
403
+ model,
404
+ PROMPT_ENHANCEMENT_STRAT,
405
+ NUM_EXISTING_SAMPLES,
406
+ eval_filepath,
407
+ final_filepath,
408
+ Retriever,
409
+ ):
410
+ # read the first four lines to determine the header
411
+
412
+ uuid_1 = get_unique_uuid()
413
+
414
+ with open("prompt-templates/system-prompt.txt", "r") as file2:
415
+ preprompt = file2.read()
416
+
417
+ # Read from evaluation dataset file:
418
+ df = pd.read_csv(eval_filepath, header=0)
419
+
420
+ for index, row in df.iterrows():
421
+ # iterate every row
422
+ # find specific column
423
+ model_evaluation(
424
+ row,
425
+ preprompt,
426
+ df,
427
+ index,
428
+ model,
429
+ PROMPT_ENHANCEMENT_STRAT,
430
+ NUM_EXISTING_SAMPLES,
431
+ Retriever,
432
+ uuid_1,
433
+ )
434
+
435
+ df.to_csv(eval_filepath, index=False, encoding="utf-8")
436
+ df.to_csv(final_filepath, index=False, encoding="utf-8")
437
+
438
+ logger.info(f"Finished evaluation for {model}")
439
+
440
+
441
+ def get_plan_result_template():
442
+ return {
443
+ "terraform_plan_success": False,
444
+ "terraform_output": "No output",
445
+ "terraform_plan_error": "No error",
446
+ "opa_evaluation_result": "No opa_result",
447
+ "opa_evaluation_error": "None",
448
+ "notes": "",
449
+ }
450
+
451
+
452
+ def empty_code_error():
453
+ logger.info("Plan considered failed since answer contains no code output.")
454
+ plan_result = get_plan_result_template()
455
+ plan_result["terraform_plan_success"] = False
456
+ plan_result["terraform_output"] = "No output"
457
+ plan_result["terraform_plan_error"] = "Empty code"
458
+ plan_result["notes"] = (
459
+ "Terraform plan considered failed since answer contains no code output."
460
+ )
461
+ return plan_result
462
+
463
+
464
+ def prompt_enhancements(prompt, PROMPT_ENHANCEMENT_STRAT, Retriever):
465
+ if PROMPT_ENHANCEMENT_STRAT == "RAG":
466
+ knowledge = rag_knowledge(Retriever, prompt)
467
+ prompt = prompt_templates.RAG_prompt(knowledge, prompt)
468
+ elif PROMPT_ENHANCEMENT_STRAT == "COT":
469
+ prompt = prompt_templates.CoT_prompt(prompt)
470
+ elif PROMPT_ENHANCEMENT_STRAT == "FSP":
471
+ prompt = prompt_templates.FSP_prompt(prompt)
472
+ else:
473
+ prompt = "Here is the actual prompt: " + prompt
474
+ return prompt
475
+
476
+
477
+ def model_evaluation(
478
+ row,
479
+ preprompt,
480
+ df,
481
+ index,
482
+ model,
483
+ PROMPT_ENHANCEMENT_STRAT,
484
+ NUM_EXISTING_SAMPLES,
485
+ Retriever,
486
+ uuid_1,
487
+ ):
488
+ """
489
+ Note: Multi-turn implies 2 turns only
490
+ """
491
+ prompt = row["Prompt"]
492
+
493
+ # Skip empty rows
494
+ if isinstance(row["Prompt"], float):
495
+ if math.isnan(row["Prompt"]):
496
+ return
497
+
498
+ prompt = prompt_enhancements(prompt, PROMPT_ENHANCEMENT_STRAT, Retriever)
499
+
500
+ policy_file = row["Rego intent"]
501
+ num_correct = 0
502
+ logger.info(f"Begin testing model: {model}")
503
+ for i in range(NUM_EXISTING_SAMPLES, NUM_SAMPLES_PER_TASK):
504
+ multi_turn_count = 1
505
+ while True:
506
+ is_empty_code = False
507
+ logger.info(f"Sample {i} for model {model}")
508
+ logger.info(f"Preprompt: {preprompt}")
509
+ logger.info(f"Prompt: {prompt}")
510
+ if model == "gpt4":
511
+ text = models.GPT4(preprompt, prompt, gpt_client)
512
+ elif model == "gpt3.5":
513
+ text = models.GPT3_5(preprompt, prompt, gpt_client)
514
+ elif model == "gemini-1.0-pro":
515
+ text = models.gemini(preprompt, prompt)
516
+ elif model == "codellama-13b":
517
+ text = models.Codellama13b(preprompt, prompt)
518
+ elif model == "codellama-7b":
519
+ text = models.Codellama7b(preprompt, prompt)
520
+ elif model == "codellama-34b":
521
+ text = models.Codellama34b(preprompt, prompt)
522
+ elif model == "Magicoder_S_CL_7B":
523
+ text = models.Magicoder_S_CL_7B(preprompt, prompt)
524
+ elif model == "Wizardcoder33b":
525
+ text = models.Wizardcoder33b(preprompt, prompt)
526
+ elif model == "Wizardcoder34b":
527
+ text = models.Wizardcoder34b(preprompt, prompt)
528
+
529
+ logger.info(f"Model raw output: {text}")
530
+
531
+ answer, code = separate_answer_and_code(text, DELIMITERS)
532
+ if code == "":
533
+ logger.error("Error: Answer contains no code, skipping eval_pipeline.")
534
+ is_empty_code = True
535
+ logger.info("Answer is: {}".format(answer))
536
+ logger.info("Code is: {}".format(code))
537
+
538
+ df.at[index, "LLM Output #" + str(i)] = text
539
+ if is_empty_code:
540
+ x = empty_code_error()
541
+ else:
542
+ x = eval_pipeline(code, policy_file, prompt, uuid_1)
543
+ df.at[index, "LLM Plannable? #" + str(i)] = x["terraform_plan_success"]
544
+ df.at[index, "LLM Correct? #" + str(i)] = x["opa_evaluation_result"]
545
+ df.at[index, "LLM Plan Phase Error #" + str(i)] = x["terraform_plan_error"]
546
+ df.at[index, "LLM OPA match phase Error #" + str(i)] = x[
547
+ "opa_evaluation_error"
548
+ ]
549
+ df.at[index, "LLM Notes #" + str(i)] = x["notes"]
550
+ logging.info("Plan Result Summary:")
551
+ for key, value in x.items():
552
+ logging.info(f"{key}: {value}")
553
+
554
+ if x["opa_evaluation_result"] == "success":
555
+ num_correct += 1
556
+ break
557
+ elif PROMPT_ENHANCEMENT_STRAT == "multi-turn":
558
+ if multi_turn_count == 2: # only do 2 turns
559
+ break
560
+ multi_turn_count += 1
561
+ if code == "":
562
+ continue
563
+ preprompt = prompt_templates.multi_turn_system_prompt()
564
+ if not x["terraform_plan_success"]:
565
+ prompt = prompt_templates.multi_turn_plan_error_prompt(
566
+ row["Prompt"], code, x["terraform_plan_error"]
567
+ )
568
+ elif x["opa_evaluation_result"] == "Failure":
569
+ prompt = prompt_templates.multi_turn_rego_error_prompt(
570
+ row["Prompt"], code, policy_file, x["opa_evaluation_error"]
571
+ )
572
+ continue
573
+ else:
574
+ break
575
+
576
+
577
+ # used to modify main.tf
578
+ def write_to_terraform(result, terraform_dir="./terraform_config"):
579
+ # define the path to the main.tf file
580
+ os.makedirs(terraform_dir, exist_ok=True)
581
+ terraform_file_path = terraform_dir + "/main.tf"
582
+ # open the file in write mode ('w') and write the result to it
583
+ # print("CWD", os.getcwd())
584
+ logger.debug("CWD: {}".format(os.getcwd()))
585
+ with open(terraform_file_path, "w+", encoding="utf-8", errors="ignore") as file:
586
+ file.write(result)
587
+ # print(f"Updated main.tf at {terraform_file_path}")
588
+ logger.info(f"Updated main.tf at {terraform_file_path}")
589
+
590
+
591
+ # used for modify policy.rego
592
+ def write_to_rego(policy_content, rego_policy_filepath):
593
+ # define the path to the policy.rego file
594
+ # rego_file_path = "./rego_config/policy.rego"
595
+ # ensure the rego_config directory exists
596
+ os.makedirs(os.path.dirname(rego_policy_filepath), exist_ok=True)
597
+ # open the file in write mode ('w') and write the policy content to it
598
+ with open(rego_policy_filepath, "w", encoding="utf-8", errors="ignore") as file:
599
+ file.write(policy_content)
600
+ logger.info(f"Updated policy.rego at {rego_policy_filepath}")
601
+
602
+
603
+ def get_unique_uuid():
604
+ terraform_dir_prefix = "./tmp/terraform_config/"
605
+ uuid_1 = ""
606
+ while True:
607
+ uuid_1 = str(uuid.uuid4())
608
+ terraform_dir = terraform_dir_prefix + uuid_1
609
+ if os.path.isfile(terraform_dir):
610
+ continue
611
+ else:
612
+ break
613
+ return uuid_1
614
+
615
+
616
+ def eval_pipeline(result, policy_file, prompt, uuid_1):
617
+ """
618
+ TF Plan -> OPA Rego
619
+ """
620
+
621
+ # object to store the results
622
+ plan_result = get_plan_result_template()
623
+ # Clear the terraform_config directory
624
+
625
+ # Generate unique filename suffix:
626
+ terraform_dir_prefix = "./tmp/terraform_config/"
627
+ terraform_dir = terraform_dir_prefix + uuid_1
628
+
629
+ delete_all_files_in_directory(terraform_dir)
630
+
631
+ # write result to main.tf
632
+ write_to_terraform(result, terraform_dir)
633
+
634
+ # run terraform plan and capture the output and errors
635
+ plan_file = "plan.out"
636
+ plan_output, plan_error, plan_success = run_terraform_plan(
637
+ terraform_dir, plan_file, prompt
638
+ )
639
+ # print("plan output: ", plan_output)
640
+ logger.info("plan_output: {}".format(plan_output))
641
+ # print("plan_error: ", plan_error)
642
+ logger.error("plan_error occurred: {}".format(plan_error), exc_info=True)
643
+ # print("plan_success: ", plan_success)
644
+ logger.debug("plan_success: {}".format(plan_success))
645
+ plan_output = remove_unwanted_characters(plan_output)
646
+ plan_error = remove_unwanted_characters(plan_error)
647
+ plan_result["terraform_plan_success"] = plan_success
648
+ plan_result["terraform_output"] = plan_output
649
+ plan_result["terraform_plan_error"] = plan_error
650
+
651
+ if plan_success:
652
+ # print("Plan succeeded.")
653
+ logger.info("Plan succeeded.")
654
+ # go to opa rego check
655
+ rego_dir = "./tmp/rego_config/" + uuid_1
656
+ rego_policy_filepath = rego_dir + "/policy.rego"
657
+ write_to_rego(policy_file, rego_policy_filepath)
658
+ generate_terraform_plan_json("plan.json", plan_file, terraform_dir)
659
+ tf_json_plan_filepath = os.path.join(terraform_dir, "plan.json")
660
+
661
+ # run OPA evaluation and capture the result
662
+ opa_result, opa_error = OPA_Rego_evaluation(
663
+ tf_json_plan_filepath, rego_policy_filepath
664
+ )
665
+ # print("OPA result: ", opa_result)
666
+ logger.info("OPA result: {}".format(opa_result))
667
+ # print("OPA current directory: ", os.getcwd())
668
+ # print("OPA error: ", opa_error)
669
+ logger.error("OPA error occurred: {}".format(opa_error), exc_info=True)
670
+ plan_result["opa_evaluation_result"] = opa_result
671
+ plan_result["opa_evaluation_error"] = opa_error
672
+ else:
673
+ # print("Plan failed.")
674
+ logger.info("Plan failed.")
675
+ plan_result["notes"] = "Terraform plan failed."
676
+ return plan_result
677
+
678
+
679
+ def run_terraform_plan(terraform_directory, plan_file, prompt):
680
+ cur_dir = os.getcwd()
681
+ # change to the Terraform directory
682
+ os.chdir(terraform_directory)
683
+ # run init before plan
684
+ subprocess.run(["terraform", "init"], capture_output=True, text=True)
685
+
686
+ # run 'terraform plan'
687
+ # result = subprocess.run(["terraform", "plan"], capture_output=True, text=True)
688
+
689
+ result_returned = False
690
+ # generate Terraform plan with the -no-color flag
691
+ for i in range(2): # try twice
692
+ try:
693
+ result = subprocess.run(
694
+ ["terraform", "plan", "-out", plan_file, "-no-color"],
695
+ capture_output=True,
696
+ text=True,
697
+ timeout=100, # 5 minutes timeout (assume failed if timeout)
698
+ )
699
+ if "Inconsistent dependency lock file" in result.stderr:
700
+ subprocess.run(["terraform", "init"], capture_output=True, text=True)
701
+ time.sleep(10)
702
+ continue
703
+
704
+ result_returned = True
705
+ break
706
+ except Exception as e:
707
+ logging.error(
708
+ 'Error occurred for prompt "{}": {}'.format(prompt, e), exc_info=True
709
+ )
710
+
711
+ # Return to parent directory
712
+ os.chdir(cur_dir)
713
+
714
+ if not result_returned:
715
+ return "Plan timed-out. No output", "Plan timed-out. No error", False
716
+
717
+ # check the exit code and return the output, error message, and success flag
718
+ success = result.returncode == 0
719
+ output = result.stdout if not success else "success"
720
+ error = result.stderr if not success else "No error"
721
+ return output, error, success
722
+
723
+
724
+ def check_if_rego_v1(policy_file):
725
+ with open(policy_file, "r") as file:
726
+ lines = file.readlines()
727
+ for line in lines:
728
+ # if "package" in line:
729
+ if "import rego.v1" in line:
730
+ return True
731
+ return False
732
+
733
+
734
+ def OPA_Rego_evaluation(plan_file, policy_file):
735
+ # print("opa current directory: ", os.getcwd())
736
+ # assumes the current working directory is correct
737
+ try:
738
+ is_rego_v1 = check_if_rego_v1(policy_file)
739
+
740
+ if is_rego_v1:
741
+ result = subprocess.run(
742
+ [
743
+ "opa",
744
+ "eval",
745
+ "--v1-compatible",
746
+ "-i",
747
+ plan_file,
748
+ "-d",
749
+ policy_file,
750
+ "data",
751
+ ],
752
+ capture_output=True,
753
+ text=True,
754
+ )
755
+ else:
756
+ result = subprocess.run(
757
+ [
758
+ "opa",
759
+ "eval",
760
+ "-i",
761
+ plan_file,
762
+ "-d",
763
+ policy_file,
764
+ "data",
765
+ ],
766
+ capture_output=True,
767
+ text=True,
768
+ )
769
+ except Exception as e:
770
+ opa_result = "OPA exception occurred."
771
+ opa_error = "OPA exception occurred: {}".format(e)
772
+ return opa_result, opa_error
773
+
774
+ # check the exit code and return the result and error message
775
+ # success = result.returncode == 0
776
+ # key_val = next(iter( json.loads(result.stdout)["result"][0]["expressions"][0]["value"].items() ))
777
+ # get the first key-value pair: https://stackoverflow.com/a/39292086/13336187
778
+ # key_val = key_val[1]
779
+ # print(key_val)
780
+ results = [
781
+ i[-1]
782
+ for i in dict_generator(
783
+ json.loads(result.stdout)["result"][0]["expressions"][0]["value"]
784
+ )
785
+ ]
786
+ # print(results)
787
+ # print(key_val)
788
+ success = False if False in results else True
789
+ opa_result = "Success" if success else "Failure"
790
+ opa_error = "No error"
791
+ if not success:
792
+ opa_error = "Rule violation found. OPA complete output logged here: " + str(
793
+ json.loads(result.stdout)
794
+ )
795
+ # print("OPA error: ", opa_error)
796
+ return opa_result, opa_error
797
+
798
+
799
+ def generate_terraform_plan_json(
800
+ output_json_file, plan_file="plan.out", terraform_dir="./terraform_config"
801
+ ):
802
+ try:
803
+ cur_dir = os.getcwd()
804
+ os.chdir(terraform_dir)
805
+ # init_result = subprocess.run(["terraform", "init"], check=True)
806
+
807
+ # # generate Terraform plan with the -no-color flag
808
+ # plan_file = "plan.out"
809
+ # plan_result = subprocess.run(
810
+ # ["terraform", "plan", "-out", plan_file, "-no-color"], check=True
811
+ # )
812
+
813
+ # convert the plan to JSON and store it
814
+ with open(
815
+ output_json_file, "w", encoding="utf-8", errors="ignore"
816
+ ) as json_file:
817
+ subprocess.run(
818
+ ["terraform", "show", "-json", plan_file], check=True, stdout=json_file
819
+ )
820
+ os.chdir(cur_dir)
821
+ except subprocess.CalledProcessError as e:
822
+ # print(f"An error occurred: {e}")
823
+ logger.error("An error occurred: {}".format(e), exc_info=True)
824
+ return None
825
+
826
+
827
+ def read_eval_models(ctx: click.Context, _, arg: str) -> List[str]:
828
+ return arg.split(sep=",")
829
+
830
+
831
+ def read_config_file(path: Path) -> Tuple[int, List[str]]:
832
+ try:
833
+ with path.open("r") as file:
834
+ config = json.load(file)
835
+ return config.get("samples", NUM_SAMPLES_PER_TASK), config.get(
836
+ "models", EVAL_MODELS
837
+ )
838
+ except BaseException:
839
+ print("Invalid config file.", file=sys.stderr)
840
+ sys.exit(1)
841
+
842
+
843
+ def set_logger(log_file: Path):
844
+ """
845
+ Set global logger with log file
846
+ """
847
+ logger.setLevel(logging.DEBUG)
848
+ # Setup File handler: https://stackoverflow.com/a/24507130/13336187
849
+ file_handler = logging.FileHandler(log_file)
850
+ file_handler.setFormatter(CustomFormatter())
851
+ file_handler.setLevel(logging.DEBUG)
852
+ # Setup Stream Handler (i.e. console)
853
+ ch = logging.StreamHandler()
854
+ ch.setLevel(logging.DEBUG)
855
+ ch.setFormatter(CustomFormatter())
856
+ # Log to both file and console:
857
+ logger.addHandler(ch)
858
+ logger.addHandler(file_handler)
859
+
860
+
861
+ def setup_gpt_client():
862
+ global gpt_client
863
+ global embeddings_model
864
+ if "OPENAI_API_KEY" not in os.environ:
865
+ api_key = input("Enter OpenAI API key:")
866
+ os.environ["OPENAI_API_KEY"] = api_key
867
+
868
+ api_key = os.environ["OPENAI_API_KEY"]
869
+
870
+ gpt_client= OpenAI(api_key=api_key)
871
+
872
+
873
+ def setup_magicoder_params():
874
+ if "MAGICODER_SAGEMAKER_ENDPOINT" not in os.environ:
875
+ endpoint = input("Enter Magicoder Sagemaker endpoint:") # E.g., "huggingface-pytorch-tgi-inference-2024-05-09-15-37-08-362"
876
+ os.environ["MAGICODER_SAGEMAKER_ENDPOINT"] = endpoint
877
+
878
+
879
+ @click.command()
880
+ @click.option(
881
+ "--samples",
882
+ "-s",
883
+ type=int,
884
+ help="Number of samples per task.",
885
+ default=NUM_SAMPLES_PER_TASK,
886
+ )
887
+ @click.option(
888
+ "--quick-test",
889
+ "-q",
890
+ "quick_test",
891
+ is_flag=True,
892
+ help="Perform quick evaluation on only 2 rows within the main dataset.",
893
+ default=False,
894
+ )
895
+ @click.option(
896
+ "--models",
897
+ "-m",
898
+ type=str,
899
+ help=f"List of evaluation models. Available models: {' '.join(EVAL_MODELS)}",
900
+ callback=read_eval_models,
901
+ default=EVAL_MODELS,
902
+ )
903
+ @click.option(
904
+ "--config",
905
+ "--file",
906
+ "-c",
907
+ "-f",
908
+ type=click.Path(path_type=Path, exists=True),
909
+ help="Path to config file for command line options.",
910
+ )
911
+ @click.option(
912
+ "--log-file",
913
+ "-l",
914
+ "log_file",
915
+ type=click.Path(path_type=Path),
916
+ help="Path to log file.",
917
+ default=DEFAULT_LOG_FILE,
918
+ )
919
+ @click.option(
920
+ "--enhance-strat",
921
+ "-e",
922
+ "enhance_strat",
923
+ type=click.Choice(PROMPT_ENHANCEMENT_STRATS),
924
+ help=f"Prompt enhancement strategy. Available strategies: {' '.join(PROMPT_ENHANCEMENT_STRATS)}",
925
+ default="",
926
+ )
927
+ # @click.argument("enhance_strat", nargs=1, type=str, default="")
928
+ def main(
929
+ samples: int, models: List[str], config: Path, log_file: Path, enhance_strat: str, quick_test: bool
930
+ ):
931
+ """
932
+ Evaluate models.
933
+ Available enhancement strategy: "RAG", "COT", "FSP", or "multi-turn".
934
+ Config file takes precedence over command line options.
935
+ """ # FIX
936
+
937
+ if config is not None:
938
+ samples, models = read_config_file(config)
939
+
940
+ # changing config variables basing on command line options
941
+ global NUM_SAMPLES_PER_TASK
942
+ NUM_SAMPLES_PER_TASK = samples
943
+ global EVAL_MODELS
944
+ EVAL_MODELS = models
945
+
946
+ set_logger(log_file)
947
+
948
+ print(samples)
949
+ print(models)
950
+
951
+ PROMPT_ENHANCEMENT_STRAT = (
952
+ enhance_strat
953
+ # FIX?: should this be changed to an option instead of argument
954
+ )
955
+
956
+ # Setup environment variables:
957
+ set_aws_credentials()
958
+ set_replicate_credentials()
959
+ # set_huggingface_credentials()
960
+
961
+ if "gemini-1.0-pro" in models:
962
+ set_google_credentials()
963
+
964
+ if "gpt3.5" in models or "gpt4" in models:
965
+ setup_gpt_client()
966
+
967
+ if "Magicoder_S_CL_7B" in models:
968
+ setup_magicoder_params()
969
+
970
+ # Setup retriever:
971
+ if "RAG" in PROMPT_ENHANCEMENT_STRAT:
972
+ Retriever = llama_index_retriever.Retriever(
973
+ stored_index="../retriever/aws-index",
974
+ path="../retriever/terraform-provider-aws/website/docs/r",
975
+ )
976
+ else:
977
+ Retriever = None
978
+
979
+ # Import dataset:
980
+ if not quick_test:
981
+ data.import_dataset()
982
+ else:
983
+ data.import_dataset(quick_test=True)
984
+
985
+ # specify the directory you want to search
986
+ script_dir = os.path.dirname(os.path.abspath(__file__))
987
+ data_dir = os.path.join(script_dir, "..", "data")
988
+ base_eval_dir = os.path.join(
989
+ data_dir, "..", "evaluation/tmp"
990
+ ) # should be the same as script_dir
991
+ final_eval_dir = os.path.join(data_dir, "..", "evaluation/results")
992
+ # Create evaluation directories for each data directory
993
+ # and perform model evaluation:
994
+ list_all_subdirectories_and_eval(
995
+ data_dir, base_eval_dir, final_eval_dir, PROMPT_ENHANCEMENT_STRAT, Retriever
996
+ )
997
+
998
+
999
+ if __name__ == "__main__":
1000
+ main()
human_reference_dataset/iac-eval/evaluation/llm-judge-eval.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Conceptual Reference: https://arxiv.org/pdf/2306.05685
2
+ import os
3
+ from pathlib import Path
4
+ from openai import OpenAI
5
+ import sys
6
+ import pandas as pd
7
+ import logging
8
+ from os import listdir
9
+ from os.path import isfile, join
10
+ import numpy as np
11
+ import math
12
+ import json
13
+ import metrics
14
+ import eval
15
+ import models
16
+
17
+ NUM_SAMPLES_PER_TASK = 1 # number of times we want to run the LLM judge for each eval output (i.e., LLM output # X) from the dataset
18
+
19
+ LOG_FILE = "logs/metrics_eval.log"
20
+ DELIMITERS = ["```hcl", "```json", "```HCL", "```Terraform", "```terraform", "```"] # ``` needs to be in the end, as it is a final "else" case
21
+
22
+ class CustomFormatter(logging.Formatter):
23
+ # https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
24
+ grey = "\x1b[38;20m"
25
+ cyan = "\x1b[36;20m"
26
+ blue = "\x1b[34:20m"
27
+ yellow = "\x1b[33;20m"
28
+ red = "\x1b[31;20m"
29
+ bold_red = "\x1b[31;1m"
30
+ reset = "\x1b[0m"
31
+ format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
32
+
33
+ FORMATS = {
34
+ logging.DEBUG: cyan + format + reset,
35
+ logging.INFO: blue + format + reset,
36
+ logging.WARNING: yellow + format + reset,
37
+ logging.ERROR: red + format + reset,
38
+ logging.CRITICAL: bold_red + format + reset
39
+ }
40
+
41
+ def format(self, record):
42
+ log_fmt = self.FORMATS.get(record.levelno)
43
+ formatter = logging.Formatter(log_fmt)
44
+ return formatter.format(record)
45
+
46
+ logger = logging.getLogger("iac-eval-metric")
47
+ logger.setLevel(logging.DEBUG)
48
+ #Setup File handler: https://stackoverflow.com/a/24507130/13336187
49
+ file_handler = logging.FileHandler(LOG_FILE)
50
+ file_handler.setFormatter(CustomFormatter())
51
+ file_handler.setLevel(logging.DEBUG)
52
+ #Setup Stream Handler (i.e. console)
53
+ ch = logging.StreamHandler()
54
+ ch.setLevel(logging.DEBUG)
55
+ ch.setFormatter(CustomFormatter())
56
+ # Log to both file and console:
57
+ logger.addHandler(ch)
58
+ logger.addHandler(file_handler)
59
+
60
+ def setup_gpt_client():
61
+ global gpt_client
62
+ global embeddings_model
63
+ if "OPENAI_API_KEY" not in os.environ:
64
+ api_key = input("Enter OpenAI API key:")
65
+ os.environ["OPENAI_API_KEY"] = api_key
66
+
67
+ api_key = os.environ["OPENAI_API_KEY"]
68
+
69
+ gpt_client= OpenAI(api_key=api_key)
70
+
71
+ # split the code for results
72
+ def extract_rating_from_answer(text):
73
+ rating_str = text.splitlines()[-1]
74
+ if "Correct" or "Incorrect" in rating_str:
75
+ return rating_str
76
+ else:
77
+ logger.error("Error: Answer contains no code, skipping eval_pipeline.")
78
+ return rating_str
79
+
80
+ # Take our existing dataset, iterate through each row, add a new column with the LLM generated response, and a new column for the extracted verdict, and save the new dataset to a new file with a filename that is prefixed with the llm model-name.
81
+ def list_all_subdirectories(data_dir):
82
+ onlyfiles = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk(data_dir) for f in filenames]
83
+ onlyfilescsv = [f for f in onlyfiles if f.endswith(".csv")]
84
+ return onlyfilescsv
85
+
86
+ def create_new_dirs_for_metric(base_eval_files, new_base_metric_dir="llm-judge-evaluation-metric"):
87
+ for file in base_eval_files:
88
+ # create the directory if it does not exist
89
+ new_dir_path = os.path.join(os.path.dirname(file), new_base_metric_dir)
90
+ os.makedirs(new_dir_path, exist_ok=True)
91
+
92
+ def determine_eval_samples(df_columns):
93
+ """
94
+ Determine the number of samples per task
95
+ """
96
+ num_samples = 0
97
+ for col in df_columns:
98
+ if "LLM Correct?" in col:
99
+ num_samples += 1
100
+ return num_samples
101
+
102
+ def copy_csv_to_metric(base_eval_files, new_base_metric_dir, llm="gpt4"):
103
+ """
104
+ Example:
105
+ base_eval_files: ["../results-for-iac-eval (backup)/george-existing/evaluation-dataset-george-gpt3.5.csv"]
106
+ llm_base_eval_dir: "../results-for-iac-eval (backup)/george-existing/llm-judge-evaluation-metric"
107
+ """
108
+ dst_filenames = []
109
+ dst_filenames_skipped = []
110
+ llm_single_filename_prefix = "{}-single".format(llm)
111
+ llm_reference_filename_prefix = "{}-reference".format(llm)
112
+ for file in base_eval_files:
113
+ file_stem = Path(file).stem # https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
114
+ filename = llm_single_filename_prefix + "-" + file_stem + ".csv"
115
+ dest_file_path = os.path.join(os.path.dirname(file), new_base_metric_dir, filename)
116
+ # print(dest_file_path)
117
+ # Check if llm-judge file is already evaluated: skip if true
118
+ if os.path.isfile(dest_file_path) and os.stat(dest_file_path).st_size != 0: # if file is not empty
119
+ dst_df = pd.read_csv(dest_file_path, header=None)
120
+ new_header = dst_df.iloc[0]
121
+ dst_df = dst_df[1:]
122
+ dst_df.columns = new_header
123
+ dst_df.reset_index(drop=True, inplace=True)
124
+ # print(dst_df['gpt4 Judge Output #0 for LLM output #0'].iloc[0])
125
+ if not pd.isnull(dst_df['gpt4 Judge Output #0 for LLM output #0'].iloc[0]):
126
+ # print("hi: ", dest_file_path)
127
+ # while True:
128
+ # x=1
129
+ dst_filenames_skipped.append(dest_file_path)
130
+ continue
131
+ # print("no hi", dest_file_path)
132
+ # while True:
133
+ # x=1
134
+ dst_filenames.append(dest_file_path)
135
+ df = pd.read_csv(file, header=None)
136
+ new_header = df.iloc[0]
137
+ df = df[1:]
138
+ df.columns = new_header
139
+ NUM_EVAL_SAMPLES = determine_eval_samples(df.columns)
140
+ # reset the index of the DataFrame
141
+ df.reset_index(drop=True, inplace=True)
142
+ # add new columns only to df
143
+ for i in range(NUM_SAMPLES_PER_TASK):
144
+ for col_base in [
145
+ "{} Judge Output #{} for LLM output #{}".format(llm, str(i), str(0)),
146
+ "{} Judge verdict #{} for LLM output #{}".format(llm, str(i), str(0)),
147
+ ]:
148
+ df[col_base] = ""
149
+
150
+ df.to_csv(dest_file_path, index=False, encoding="utf-8")
151
+ # print(f"Copied and modified CSV to: {dest_file_path}")
152
+ return dst_filenames, dst_filenames_skipped
153
+
154
+ def llm_judge_eval_loop(dst_filenames, llm="", METRIC="llm-single"):
155
+ for file in dst_filenames:
156
+ df = pd.read_csv(file)
157
+ logger.info(f"Begin extracting metric from dataset {file}")
158
+ # while True:
159
+ # x=1
160
+ # iterate through each row
161
+ for index, row in df.iterrows():
162
+ # iterate every row
163
+ # find specific column
164
+ llm_judge_eval(row, df, index, llm, METRIC)
165
+
166
+ df.to_csv(file, index=False, encoding="utf-8")
167
+
168
+ logger.info(f"Finished extracting metric from dataset {file}")
169
+
170
+ def get_prompt_from_metric(prompt, candidate, reference, llm="", METRIC="llm-single"):
171
+ if METRIC == "llm-single":
172
+ prompt = metrics.llm_as_judge_single(prompt, candidate)
173
+ else:
174
+ assert 1 == 0, "Invalid METRIC"
175
+ return prompt
176
+
177
+ def llm_judge_eval(row, df, index, model="", METRIC="llm-single"):
178
+ """
179
+ Note: Multi-turn implies 2 turns only
180
+ """
181
+ prompt = row["Prompt"]
182
+ if isinstance(prompt, float):
183
+ if math.isnan(prompt):
184
+ return
185
+ reference = row["Reference output"]
186
+ preprompt = ""
187
+ # prompt = prompt_enhancements(prompt, PROMPT_ENHANCEMENT_STRAT)
188
+ # while True:
189
+ # x=1
190
+ policy_file = row["Rego intent"]
191
+ # num_correct = 0
192
+ # logger.info(f"Begin extracting metric {METRIC} from dataset:")
193
+ NUM_EVAL_SAMPLES = determine_eval_samples(df.columns)
194
+ for i in range(NUM_SAMPLES_PER_TASK):
195
+ eval_answer = row["LLM Output #{}".format(str(0))]
196
+ if isinstance(eval_answer, float) and math.isnan(eval_answer):
197
+ text = "LLM output in dataset is Nan"
198
+ rating_str = "No output"
199
+ else:
200
+ logger.info(f"Model raw output (already in the dataset itself, for when evaluating a model on the dataset): {eval_answer}")
201
+ answer, candidate = eval.separate_answer_and_code(eval_answer, DELIMITERS)
202
+ logger.info(f"Candidate config: {candidate}")
203
+
204
+ prompt = get_prompt_from_metric(prompt, candidate=candidate, reference=reference, llm=model, METRIC=METRIC)
205
+
206
+ logger.info(f"Sample {i} for metric {METRIC}")
207
+ logger.info(f"Preprompt: {preprompt}")
208
+ logger.info(f"Prompt: {prompt}")
209
+ if model == "gpt4":
210
+ text = models.GPT4(preprompt, prompt, gpt_client)
211
+ elif model == "gpt3.5":
212
+ text = models.GPT3_5(preprompt, prompt, gpt_client)
213
+ elif model == "gemini-1.0-pro":
214
+ text = models.gemini(preprompt, prompt)
215
+ elif model == "codellama-13b":
216
+ text = models.Codellama13b(preprompt, prompt)
217
+ elif model == "codellama-7b":
218
+ text = models.Codellama7b(preprompt, prompt)
219
+ elif model == "codellama-34b":
220
+ text = models.Codellama34b(preprompt, prompt)
221
+
222
+ rating_str = extract_rating_from_answer(text)
223
+ logger.info("Answer is: {}".format(text))
224
+ logger.info("Rating is: {}".format(rating_str))
225
+
226
+ df.at[index, "{} Judge Output #{} for LLM output #{}".format(model, str(i), str(0))] = text
227
+ df.at[index, "{} Judge verdict #{} for LLM output #{}".format(model, str(i), str(0))] = rating_str
228
+
229
+ # return text
230
+
231
+ # main:
232
+ def main(): # E.g.,: python3 llm-judge-eval.py gpt4 llm-single
233
+ llm = sys.argv[1] # options: gpt4
234
+ metric = sys.argv[2] # options: "llm-single"
235
+ script_dir = os.path.dirname(os.path.abspath(__file__))
236
+ eval_data_dir = os.path.join(script_dir, "results")
237
+ base_eval_files = list_all_subdirectories(eval_data_dir)
238
+ base_eval_files = [f for f in base_eval_files if "-single" not in f and "-reference" not in f]
239
+ print(base_eval_files)
240
+
241
+ base_eval_files = [f for f in base_eval_files if "COT" not in f and "FSP" not in f and "RAG" not in f and "multi-turn" not in f] # temporarily to save time...
242
+ print(base_eval_files)
243
+
244
+ # base_eval_files = ['/home/ubuntu/autoiac-tasks/evaluation/../results-for-iac-eval (backup)/multi-turn/gpt4/lei-existing/evaluation-dataset-multi-turn-lei-gpt4-test-1.csv'] # just for debugging purposes
245
+
246
+ create_new_dirs_for_metric(base_eval_files, new_base_metric_dir="llm-judge-evaluation-metric")
247
+ dst_filenames, dst_filenames_skipped = copy_csv_to_metric(base_eval_files, new_base_metric_dir="llm-judge-evaluation-metric", llm="gpt4")
248
+
249
+ print("Filenames to evaluate: ", dst_filenames)
250
+ print("------------------------------")
251
+ print("Filenames skipped (since they have already been evaluated): ", dst_filenames_skipped)
252
+ # Write dst_filenames to a file:
253
+ # with open("delete-soon-archived/dst_filenames.txt", "w") as f:
254
+ # for item in dst_filenames:
255
+ # f.write("%s\n" % item)
256
+ # while True:
257
+ # x=1
258
+ llm_judge_eval_loop(dst_filenames, llm=llm, METRIC=metric)
259
+ # At the end, get a correctness percentage across all rows in the dataset (across all files).
260
+
261
+ if __name__ == "__main__":
262
+ setup_gpt_client()
263
+ main()
human_reference_dataset/iac-eval/evaluation/logs/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Stores log files for various evaluation tasks.
human_reference_dataset/iac-eval/evaluation/metrics.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BLEU
2
+ from nltk.translate.bleu_score import sentence_bleu, corpus_bleu, SmoothingFunction
3
+ import code_bert_score
4
+ # reference = [['this', 'is', 'a', 'test'], ['this', 'is' 'test']]
5
+ # candidate = ['this', 'is', 'a', 'test']
6
+ # score = sentence_bleu(reference, candidate)
7
+ # print(score)
8
+ # Exact match:
9
+ def bleu_score(reference, candidate):
10
+ reference_tokens = reference.split()
11
+ result_tokens = candidate.split()
12
+ if len(reference_tokens) < 4:
13
+ print("Reference code has less than 4 tokens:".format(reference))
14
+ return 0
15
+ if len(result_tokens) < 4:
16
+ print("Result code has less than 4 tokens:".format(candidate))
17
+ return 0
18
+ score = corpus_bleu([[reference_tokens]], [result_tokens], weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=SmoothingFunction().method3)
19
+ # A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0. Standard implementation from NLTK based on the actual paper.
20
+ # return sentence_bleu(reference, candidate)
21
+ return score
22
+
23
+ def get_code_bert_score(reference, candidate, prompt):
24
+ # https://github.com/neulab/code-bert-score
25
+ pred_results = code_bert_score.score(cands=[candidate], refs=[reference], lang='python', sources=[prompt]) # returns a 4-tuple of (precision, recall, F1, F3), where each is a 1-D tensor of scores for each prediction-reference pair
26
+ return {
27
+ "precision": pred_results[0].item(),
28
+ "recall": pred_results[1].item(),
29
+ "f1": pred_results[2].item(),
30
+ "f3": pred_results[3].item()
31
+ }
32
+
33
+ def exact_match(reference, candidate):
34
+ return reference.strip() == candidate.strip()
35
+
36
+ def llm_as_judge_single(prompt, candidate):
37
+ # Fig 6 of the paper: https://arxiv.org/pdf/2306.05685
38
+ template = """
39
+ Please act as an impartial judge and evaluate the correctness of the code provided by an AI assistant to the user question displayed below. Begin your evaluation by providing a short explanation. Be as objective as possible. After providing your explanation, please rate the response as either correct or incorrect by strictly following this format: "Rating: Correct" or "Rating: Incorrect".
40
+
41
+ [Question]
42
+ {}
43
+
44
+ [The Start of Assistant’s Answer]
45
+ {}
46
+ [The End of Assistant’s Answer]
47
+ """.format(prompt, candidate)
48
+ # return bleu_score(reference, candidate)
49
+ return template
50
+
51
+ def llm_as_judge_reference(reference, candidate, llm="gpt4"):
52
+ # Fig 8 of the paper: https://arxiv.org/pdf/2306.05685. Edited to not have an "assistant B".
53
+ template = """
54
+ Please act as an impartial judge and evaluate the correctness of the code provided by an AI assistant to the user question displayed below. You will be given a reference answer, and the assistant's answer. Your job is to evaluate if the assistant's answer is correct or incorrect, in comparison to the reference answer. Begin your evaluation by comparing the assistant's answer with the reference answer. Identify and correct any mistakes. Avoid any position biases and ensure that the order in which the responses were presented does not influence your decision. Do not allow the length of the responses to influence your evaluation. Be as objective as possible. After providing your explanation, output your final verdict by strictly following this format: "Rating: Correct" or "Rating: Incorrect".
55
+
56
+ [User Question]
57
+ {}
58
+
59
+ [The Start of Reference Answer]
60
+ {}
61
+ [The End of Reference Answer]
62
+
63
+ [The Start of Assistant’s Answer]
64
+ {}
65
+ [The End of Assistant’s Answer]
66
+ """.format(prompt, reference, candidate)
67
+
68
+ # return bleu_score(reference, candidate)
69
+ return template
70
+
71
+ # reference = """
72
+ # terraform {
73
+ # required_providers {
74
+ # aws = {
75
+ # source = "hashicorp/aws"
76
+ # version = "~> 4.16"
77
+ # }
78
+ # }
79
+
80
+ # required_version = ">= 1.2.0"
81
+ # }
82
+
83
+ # provider "aws" {
84
+ # region = "us-west-2"
85
+ # }
86
+
87
+ # resource "aws_iam_role" "test_role" {
88
+ # name = "test_role"
89
+
90
+ # assume_role_policy = jsonencode({
91
+ # Version = "2012-10-17"
92
+ # Statement = [
93
+ # {
94
+ # Action = "sts:AssumeRole"
95
+ # Effect = "Allow"
96
+ # Sid = ""
97
+ # Principal = {
98
+ # Service = "codebuild.amazonaws.com"
99
+ # }
100
+ # },
101
+ # ]
102
+ # })
103
+
104
+ # tags = {
105
+ # tag-key = "test_role"
106
+ # }
107
+ # }
108
+
109
+
110
+ # resource "aws_codebuild_project" "example" {
111
+ # name = "test-project"
112
+ # service_role = aws_iam_role.test_role.arn
113
+
114
+ # artifacts {
115
+ # type = "NO_ARTIFACTS"
116
+ # }
117
+
118
+ # environment {
119
+ # compute_type = "BUILD_GENERAL1_SMALL"
120
+ # image = "aws/codebuild/amazonlinux2-x86_64-standard:4.0"
121
+ # type = "LINUX_CONTAINER"
122
+ # image_pull_credentials_type = "CODEBUILD"
123
+
124
+ # }
125
+
126
+ # source {
127
+ # type = "GITHUB"
128
+ # location = "https://github.com/neilbalch/SimplePythonTutorial.git"
129
+ # git_clone_depth = 1
130
+ # }
131
+ # }terraform {
132
+ # required_providers {
133
+ # aws = {
134
+ # source = "hashicorp/aws"
135
+ # version = "~> 4.16"
136
+ # }
137
+ # }
138
+
139
+ # required_version = ">= 1.2.0"
140
+ # }
141
+
142
+ # provider "aws" {
143
+ # region = "us-west-2"
144
+ # }
145
+ # """
146
+
147
+
148
+ # candidate = """
149
+ # resource "aws_codebuild_project" "example" {
150
+ # name = "example"
151
+ # description = "Example CodeBuild project"
152
+ # source {
153
+ # type = "GITHUB"
154
+ # location = "https://github.com/hashicorp/example-codebuild"
155
+ # }
156
+ # artifacts {
157
+ # type = "CODEPIPELINE"
158
+ # location = "codepipeline"
159
+ # path = "output"
160
+ # namespace_type = "NONE"
161
+ # }
162
+ # environment {
163
+ # type = "LINUX_CONTAINER"
164
+ # image = "aws/codebuild/standard:5.0"
165
+ # compute_type = "BUILD_GENERAL1_SMALL"
166
+ # }
167
+ # service_role = "arn:aws:iam::111122223333:role/example-codebuild-role"
168
+ # }
169
+
170
+ # resource "aws_iam_role" "example" {
171
+ # name = "example-codebuild-role"
172
+ # assume_role_policy = jsonencode({
173
+ # Version = "2012-10-17"
174
+ # Statement = [{
175
+ # Action = "sts:AssumeRole"
176
+ # Effect = "Allow"
177
+ # Principal = {
178
+ # Service = "codebuild.amazonaws.com"
179
+ # }
180
+ # }]
181
+ # })
182
+
183
+ # inline_policy {
184
+ # name = "example"
185
+ # policy = jsonencode({
186
+ # Version = "2012-10-17"
187
+ # Statement = [{
188
+ # Action = ["codebuild:BatchGetBuilds", "codebuild:StartBuild"],
189
+ # Effect = "Allow"
190
+ # Resource = "*"
191
+ # }, {
192
+ # Action = ["ecr:GetAuthorizationToken", "ecr:PutImage"],
193
+ # Effect = "Allow"
194
+ # Resource = "arn:aws:ecr:us-west-2:111122223333:repository/example"
195
+ # }, {
196
+ # Action = ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
197
+ # Effect = "Allow"
198
+ # Resource = "arn:aws:logs:us-west-2:111122223333:log-group:/aws/codebuild/*"
199
+ # }, {
200
+ # Action = ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject"],
201
+ # Effect = "Allow"
202
+ # Resource = "arn:aws:s3:::example/*"
203
+ # }, {
204
+ # Action = ["secretsmanager:GetSecretValue"],
205
+ # Effect = "Allow"
206
+ # Resource = "arn:aws:secretsmanager:us-west-2:111122223333:secret:example"
207
+ # }]
208
+ # })
209
+ # }
210
+ # }
211
+ # """
212
+
213
+ # print(bleu_score(reference, candidate))
human_reference_dataset/iac-eval/evaluation/misc/ablation-judge/ablation-llm-judge.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Assumption: single file for each evaluated dataset. (e.g., no -pass5 and -pass1 in the same folder.)
2
+ import csv
3
+ import pandas as pd
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+ from openai import AzureOpenAI
8
+ import pandas as pd
9
+ import json
10
+ import subprocess
11
+ import copy
12
+ from io import StringIO
13
+ import re
14
+ import sys
15
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
16
+ import eval
17
+ import metrics
18
+ import math
19
+
20
+ DELIMITERS = ["```hcl", "```json", "```HCL", "```Terraform", "```terraform", "```"] # ``` needs to be in the end, as it is a final "else" case
21
+
22
+ LOG_FILE = "logs/eval-repair.log"
23
+
24
+ class CustomFormatter(logging.Formatter):
25
+ # https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
26
+ grey = "\x1b[38;20m"
27
+ cyan = "\x1b[36;20m"
28
+ blue = "\x1b[34:20m"
29
+ yellow = "\x1b[33;20m"
30
+ red = "\x1b[31;20m"
31
+ bold_red = "\x1b[31;1m"
32
+ reset = "\x1b[0m"
33
+ format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
34
+
35
+ FORMATS = {
36
+ logging.DEBUG: cyan + format + reset,
37
+ logging.INFO: blue + format + reset,
38
+ logging.WARNING: yellow + format + reset,
39
+ logging.ERROR: red + format + reset,
40
+ logging.CRITICAL: bold_red + format + reset
41
+ }
42
+
43
+ def format(self, record):
44
+ log_fmt = self.FORMATS.get(record.levelno)
45
+ formatter = logging.Formatter(log_fmt)
46
+ return formatter.format(record)
47
+
48
+ logger = logging.getLogger("iac-eval-repair")
49
+ logger.setLevel(logging.DEBUG)
50
+ #Setup File handler: https://stackoverflow.com/a/24507130/13336187
51
+ file_handler = logging.FileHandler(LOG_FILE)
52
+ file_handler.setFormatter(CustomFormatter())
53
+ file_handler.setLevel(logging.DEBUG)
54
+ #Setup Stream Handler (i.e. console)
55
+ ch = logging.StreamHandler()
56
+ ch.setLevel(logging.DEBUG)
57
+ ch.setFormatter(CustomFormatter())
58
+ # Log to both file and console:
59
+ logger.addHandler(ch)
60
+ logger.addHandler(file_handler)
61
+
62
+ def pretty_json(obj):
63
+ return json.dumps(obj, sort_keys=True, indent=4, default=str)
64
+
65
+ def estimator(n: int, c: int, k: int) -> float:
66
+ """
67
+ Calculates 1 - comb(n - c, k) / comb(n, k).
68
+ """
69
+ if n - c < k:
70
+ return 1.0
71
+ return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
72
+
73
+ def list_all_subdirectories(composition_dict, data_dir, excluded_dirs, strats=["multi-turn", "RAG", "COT", "FSP"], mandatory_substring="llm-judge-evaluation-metric"):
74
+ onlyfiles = []
75
+ for dirpath, dirnames, filenames in os.walk(data_dir):
76
+
77
+ skip_dirname = False
78
+
79
+ # Skip eval directories that were used to evaluate custom strats (e.g., RAG...), i.e., only keep standard
80
+ for dir1 in strats:
81
+ if dir1 in dirpath:
82
+ skip_dirname = True
83
+ # Keep only LLM-judge output directories
84
+ if not skip_dirname:
85
+ if mandatory_substring not in dirpath:
86
+ skip_dirname = True
87
+
88
+ if not skip_dirname:
89
+ for f in filenames:
90
+ skip_file = False
91
+ for exc in excluded_dirs:
92
+ if exc in f:
93
+ skip_file = True
94
+ if not skip_file:
95
+ onlyfiles.append(os.path.join(dirpath, f))
96
+
97
+ onlyfilescsv = [f for f in onlyfiles if f.endswith(".csv")]
98
+
99
+ # print(onlyfilescsv)
100
+ # while True:
101
+ # x=1
102
+
103
+ # Append to composition dict:
104
+ for file1 in onlyfilescsv:
105
+ dirname = os.path.dirname(file1)
106
+ # print(os.path.dirname(file1))
107
+ # while True:
108
+ # x=1
109
+ included = False
110
+ is_standard = True
111
+ for i in strats:
112
+ if i in dirname:
113
+ is_standard = False
114
+
115
+ for model, model_dict in composition_dict.items():
116
+ for strat, student_dict in model_dict.items():
117
+ if is_standard:
118
+ if strat != "Standard":
119
+ continue
120
+ for student, dataset_list in student_dict.items():
121
+ is_file = False
122
+ if is_standard:
123
+ if student in dirname and model in dirname:
124
+ is_file = True
125
+ else:
126
+ if student in dirname and strat in dirname and model in dirname:
127
+ is_file = True
128
+ if is_file:
129
+ if not included:
130
+ composition_dict[model][strat][student].append(file1)
131
+ included = True
132
+ else:
133
+ print("WARNING: This file attempted to be included multiple times: ", file1)
134
+ if not included:
135
+ print("WARNING: This file was excluded: ", file1)
136
+
137
+ return onlyfilescsv, composition_dict
138
+
139
+ def create_new_dirs_for_metric(new_base_difficulty_dir, base_dataset_files):
140
+ os.makedirs(new_base_difficulty_dir, exist_ok=True)
141
+ for file in base_dataset_files:
142
+ containing_folder = os.path.basename(os.path.dirname(file)) # e.g., weijun
143
+ filename = os.path.basename(file) # e.g., plain-dataset.csv
144
+ # create the directory if it does not exist
145
+ new_dir_path = os.path.join(new_base_difficulty_dir, containing_folder)
146
+ # print(new_dir_path)
147
+ os.makedirs(new_dir_path, exist_ok=True)
148
+
149
+ def metric_calculation_loop(composition_dict, dataset_dir, output_composition_dict_filepath):
150
+
151
+ """
152
+ Output format example (added in place to composition_dict): {
153
+ "gpt4": {
154
+ "Standard": {
155
+ ..., # whatever that is already in composition_dict
156
+ "llm-judge": {
157
+ "accuracy": 0.8,
158
+ "precision": 0.5,
159
+ "recall": 0.3
160
+ },
161
+ "iac_eval_accuracy": XYZ, # copied from ablation/output_composition_dict.json
162
+ },
163
+ "COT": <current implementation not supported>
164
+ },
165
+ "gpt3.5": {
166
+ ...
167
+ },
168
+ ...
169
+ }
170
+ """
171
+
172
+ output_composition_dict = copy.deepcopy(composition_dict) # https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python
173
+
174
+ for model, model_dict in composition_dict.items():
175
+ for strat, student_dict in model_dict.items():
176
+ num_success = 0 # row considered correct by LLM-judge pipeline correctly
177
+ num_rows = 0
178
+
179
+ true_positive_count = 0
180
+ false_positive_count = 0
181
+ false_negative_count = 0
182
+
183
+ passed_once = False
184
+
185
+ iac_eval_complexity_accuracy = {
186
+ "1": {
187
+ "num_success_both": 0,
188
+ "num_rows": 0,
189
+ },
190
+ "2": {
191
+ "num_success_both": 0,
192
+ "num_rows": 0,
193
+ },
194
+ "3": {
195
+ "num_success_both": 0,
196
+ "num_rows": 0,
197
+ },
198
+ "4": {
199
+ "num_success_both": 0,
200
+ "num_rows": 0,
201
+ },
202
+ "5": {
203
+ "num_success_both": 0,
204
+ "num_rows": 0,
205
+ },
206
+ "6": {
207
+ "num_success_both": 0,
208
+ "num_rows": 0,
209
+ }
210
+ }
211
+
212
+ for student, dataset_list in student_dict.items():
213
+ # n_total = 0 # number of trials that this student has been evaluated for. Used for pass@k's n parameter
214
+ for file1 in dataset_list:
215
+ # Go through each row
216
+ df = pd.read_csv(file1)
217
+ print(f"Begin calc metrics for dataset {file1}")
218
+
219
+ # iterate through each row
220
+ for index, row in df.iterrows():
221
+
222
+ # Skip empty rows
223
+ if isinstance(row["Prompt"], float):
224
+ if math.isnan(row["Prompt"]):
225
+ continue
226
+
227
+ print("Current Prompt: ", row["Prompt"])
228
+
229
+ passed_once = True
230
+ num_rows += 1
231
+
232
+ # TODO: May add this back in later if need it for appendix evaluation
233
+ # dataset_df, dataset_row = extract_dataset_row(row, index, df, dataset_dir, file1) # extract the corresponding row from the "data" dataset file
234
+ # complexity = difficulty_retrieval(dataset_row)
235
+
236
+ iac_eval_success = False
237
+
238
+ if row["LLM Plannable? #0"] == True: # we use #0 even if it is possible that a mistake was made somewhere and we evaluated e.g., FSP twice.
239
+ if row["LLM Correct? #0"] == "Success":
240
+ iac_eval_success = True
241
+ # iac_eval_complexity_accuracy[complexity]["num_success_both"] += 1
242
+
243
+ edge_case = False
244
+ if isinstance(row["gpt4 Judge verdict #0 for LLM output #0"], float):
245
+ edge_case = True
246
+ else:
247
+ if "Incorrect" in row["gpt4 Judge verdict #0 for LLM output #0"]:
248
+ if iac_eval_success:
249
+ false_negative_count += 1
250
+ elif "Correct" in row["gpt4 Judge verdict #0 for LLM output #0"]:
251
+ num_success += 1
252
+ if not iac_eval_success:
253
+ false_positive_count += 1
254
+ else:
255
+ true_positive_count += 1
256
+ else:
257
+ edge_case = True
258
+
259
+ if edge_case:
260
+ # in the rare edge case that this happens, we retrieve our original results and try and extract a line containing: "Rating: X":
261
+ found_rating = False
262
+ print(row["Prompt"])
263
+ print(row["gpt4 Judge Output #0 for LLM output #0"])
264
+ if "Rating: " in row["gpt4 Judge Output #0 for LLM output #0"]:
265
+ judgement_str = row["gpt4 Judge Output #0 for LLM output #0"].split("\n")
266
+ for line in judgement_str:
267
+ if "Rating: Incorrect" in line or "Rating: Correct" in line:
268
+ if "Incorrect" in line:
269
+ if iac_eval_success:
270
+ false_negative_count += 1
271
+ elif "Correct" in line:
272
+ num_success += 1
273
+ if not iac_eval_success:
274
+ false_positive_count += 1
275
+ else:
276
+ true_positive_count += 1
277
+ found_rating = True
278
+ break
279
+ if not found_rating:
280
+ # log it but continue. Currently, we observe that GPT4 rarely does not follow our instruction to output the line "Rating: Incorrect" or "Rating: Correct".
281
+ print("WARNING: Unexpected value in gpt4 Judge verdict #0 for LLM output #0: ", row["gpt4 Judge verdict #0 for LLM output #0"])
282
+ # assert False
283
+
284
+ print(f"Finished calc metrics for dataset {file1}")
285
+
286
+ if not passed_once:
287
+ continue
288
+
289
+ # Calculate metrics
290
+ if true_positive_count + false_positive_count == 0:
291
+ precision = 0
292
+ else:
293
+ precision = true_positive_count / (true_positive_count + false_positive_count)
294
+
295
+ if true_positive_count + false_negative_count == 0:
296
+ recall = 0
297
+ else:
298
+ recall = true_positive_count / (true_positive_count + false_negative_count)
299
+
300
+ output_composition_dict[model][strat]["llm-judge"] = {
301
+ "accuracy": num_success / num_rows, # in terms of the perspective of the LLM-judge, what it deems to be correct. Not the same as calculating confusion matrix accuracy
302
+ "precision": precision,
303
+ "recall": recall
304
+ }
305
+
306
+ # Copy over the IAC eval accuracy from the ablation output composition dict:
307
+ with open(os.path.join(os.path.dirname(output_composition_dict_filepath), "../ablation", "output_composition_dict.json"), 'r') as fp:
308
+ ablation_output_composition_dict = json.load(fp)
309
+ output_composition_dict[model][strat]["iac_eval_accuracy"] = ablation_output_composition_dict[model][strat]["iac_eval_accuracy"]
310
+
311
+ # for level, attrs in iac_eval_complexity_accuracy.items():
312
+ # output_composition_dict[model][strat]["iac_eval_complexity_accuracy"][level] = attrs["num_success_both"]/attrs["num_rows"]
313
+
314
+ with open(output_composition_dict_filepath, 'w') as fp: # incremental updates
315
+ json.dump(output_composition_dict, fp)
316
+
317
+ return output_composition_dict
318
+
319
+ def extract_dataset_row(eval_row, eval_index, eval_df, dataset_dir, eval_filename, strats=["multi-turn", "RAG", "COT", "FSP"]):
320
+ """
321
+ Example eval_filename: '/home/ubuntu/autoiac-tasks/evaluation/misc/ablation/../../../results-for-iac-eval (backup)/multi-turn/codellama-34b/george/evaluation-dataset-for-plain-dataset-george-existing-multi-turn.csv'
322
+ """
323
+
324
+ # Extract corresponding "data" dataset file name:
325
+ file_stem = Path(eval_filename).stem # https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
326
+ file_stem = file_stem.split("evaluation-dataset-for-")[1]
327
+ filename = ""
328
+ for i in strats:
329
+ if i in file_stem:
330
+ filename = file_stem.split("-{}".format(i))[0] + ".csv"
331
+ if filename == "":
332
+ filename = file_stem + ".csv"
333
+
334
+ filename = "completed-" + filename
335
+
336
+ containing_folder = os.path.basename(os.path.dirname(eval_filename)) # e.g., weijun
337
+ dataset_filename = os.path.join(dataset_dir, containing_folder, filename)
338
+
339
+ # Access dataset file and extract required row
340
+ df = pd.read_csv(dataset_filename, header=None)
341
+
342
+ # set the third row as the header
343
+ new_header = df.iloc[0]
344
+ df = df[1:]
345
+ df.columns = new_header
346
+ # # reset the index of the DataFrame
347
+ df.reset_index(drop=True, inplace=True)
348
+
349
+ # print(df.at[eval_index, "Prompt"])
350
+ # while True:
351
+ # x=1
352
+
353
+ # print(df)
354
+
355
+ # assert df.at[eval_index, "Prompt"] == eval_row["Prompt"] # add this back in as needed. Removed for now since I might have updated some dataset rows after some eval was performed on the old version of the dataset..
356
+
357
+ return df, df.iloc[eval_index]
358
+
359
+ def difficulty_retrieval(row, difficulty_header="Complexity"):
360
+ prompt = row["Prompt"]
361
+ if isinstance(prompt, float):
362
+ if math.isnan(prompt):
363
+ return
364
+ reference = row["Reference output"]
365
+ policy = row["Rego intent"]
366
+
367
+ print("Prompt:", prompt)
368
+
369
+ return row[difficulty_header]
370
+
371
+ def findkeys(node, kv):
372
+ # Modified from: https://stackoverflow.com/a/19871956/13336187
373
+ if isinstance(node, list):
374
+ for i in node:
375
+ for x in findkeys(i, kv):
376
+ yield x
377
+ elif isinstance(node, dict):
378
+ if kv in node:
379
+ yield kv
380
+ for j in node.values():
381
+ for x in findkeys(j, kv):
382
+ yield x
383
+
384
+ # print(list(findkeys(d, 'id')))
385
+
386
+ def write_to_terraform(result, terraform_dir="./misc/ablation/terraform_config"):
387
+ # define the path to the main.tf file
388
+ terraform_file_path = terraform_dir + "/metric-measurement-main.tf"
389
+ # open the file in write mode ('w') and write the result to it
390
+ # print("CWD", os.getcwd())
391
+ # print("CWD: {}".format(os.getcwd()))
392
+ with open(terraform_file_path, "w+", encoding="utf-8", errors="ignore") as file:
393
+ file.write(result)
394
+ # print(f"Updated main.tf at {terraform_file_path}")
395
+ # print(f"Updated main.tf at {terraform_file_path}")
396
+
397
+ def generate_terraform_plan_json(prompt, terraform_dir="./misc/ablation/terraform_config", plan_file="plan.out", output_json_file="plan.json"):
398
+ cwd = os.getcwd()
399
+ # change to the Terraform directory
400
+ os.chdir(terraform_dir)
401
+ # run init before plan
402
+ init_result = subprocess.run(["terraform", "init"], capture_output=True, text=True)
403
+
404
+ # run 'terraform plan'
405
+ # result = subprocess.run(["terraform", "plan"], capture_output=True, text=True)
406
+
407
+ result_returned = False
408
+ # generate Terraform plan with the -no-color flag
409
+ for i in range(2): # try twice
410
+ try:
411
+ result = subprocess.run(
412
+ ["terraform", "plan", "-out", plan_file, "-no-color"], capture_output=True, text=True, timeout=300 # 5 minutes timeout (assume failed if timeout)
413
+ )
414
+
415
+ with open(
416
+ output_json_file, "w", encoding="utf-8", errors="ignore"
417
+ ) as json_file:
418
+ show_result = subprocess.run(
419
+ ["terraform", "show", "-json", plan_file], check=True, stdout=json_file
420
+ )
421
+
422
+ result_returned = True
423
+ break
424
+ except Exception as e:
425
+ print("Error occurred for prompt \"{}\": {}".format(prompt, e))
426
+
427
+ # Return to parent directory
428
+ os.chdir(cwd)
429
+
430
+ if result_returned == False:
431
+ return "Plan timed-out. No output", "Plan timed-out. No error", False
432
+
433
+
434
+ def main():
435
+ # Find dataset files:
436
+ script_dir = os.path.dirname(os.path.abspath(__file__))
437
+ eval_dataset_dir = os.path.join(script_dir, "../..", "results")
438
+ dataset_dir = os.path.join(script_dir, "../complete-dataset-measurement/complete-dataset")
439
+ # print()
440
+ excluded_dirs = ["pass"] # skip filenames containing "pass". will merge them into a regular file once done with eval..
441
+ composition_dict = {
442
+ "gpt4": {
443
+ "COT": {
444
+ "complete": [],
445
+ },
446
+ "FSP": {
447
+ "complete": [],
448
+ },
449
+ "multi-turn": {
450
+ "complete": [],
451
+ },
452
+ "RAG": {
453
+ "complete": [],
454
+ },
455
+ "Standard": {
456
+ "complete": [],
457
+ },
458
+ },
459
+ "gpt3.5": {
460
+ "COT": {
461
+ "complete": [],
462
+ },
463
+ "FSP": {
464
+ "complete": [],
465
+ },
466
+ "multi-turn": {
467
+ "complete": [],
468
+ },
469
+ "RAG": {
470
+ "complete": [],
471
+ },
472
+ "Standard": {
473
+ "complete": [],
474
+ },
475
+ },
476
+ "gemini-1.0-pro": {
477
+ "COT": {
478
+ "complete": [],
479
+ },
480
+ "FSP": {
481
+ "complete": [],
482
+ },
483
+ "multi-turn": {
484
+ "complete": [],
485
+ },
486
+ "RAG": {
487
+ "complete": [],
488
+ },
489
+ "Standard": {
490
+ "complete": [],
491
+ },
492
+ },
493
+ "codellama-34b": {
494
+ "COT": {
495
+ "complete": [],
496
+ },
497
+ "FSP": {
498
+ "complete": [],
499
+ },
500
+ "multi-turn": {
501
+ "complete": [],
502
+ },
503
+ "RAG": {
504
+ "complete": [],
505
+ },
506
+ "Standard": {
507
+ "complete": [],
508
+ },
509
+ },
510
+ "codellama-13b": {
511
+ "COT": {
512
+ "complete": [],
513
+ },
514
+ "FSP": {
515
+ "complete": [],
516
+ },
517
+ "multi-turn": {
518
+ "complete": [],
519
+ },
520
+ "RAG": {
521
+ "complete": [],
522
+ },
523
+ "Standard": {
524
+ "complete": [],
525
+ },
526
+ },
527
+ "codellama-7b": {
528
+ "COT": {
529
+ "complete": [],
530
+ },
531
+ "FSP": {
532
+ "complete": [],
533
+ },
534
+ "multi-turn": {
535
+ "complete": [],
536
+ },
537
+ "RAG": {
538
+ "complete": [],
539
+ },
540
+ "Standard": {
541
+ "complete": [],
542
+ },
543
+ },
544
+ "Magicoder_S_CL_7B": {
545
+ "COT": {
546
+ "complete": [],
547
+ },
548
+ "FSP": {
549
+ "complete": [],
550
+ },
551
+ "multi-turn": {
552
+ "complete": [],
553
+ },
554
+ "RAG": {
555
+ "complete": [],
556
+ },
557
+ "Standard": {
558
+ "complete": [],
559
+ },
560
+ },
561
+ "Wizardcoder33b": {
562
+ "COT": {
563
+ "complete": [],
564
+ },
565
+ "FSP": {
566
+ "complete": [],
567
+ },
568
+ "multi-turn": {
569
+ "complete": [],
570
+ },
571
+ "RAG": {
572
+ "complete": [],
573
+ },
574
+ "Standard": {
575
+ "complete": [],
576
+ },
577
+ }
578
+ }
579
+ eval_dataset_files, composition_dict = list_all_subdirectories(composition_dict, eval_dataset_dir, excluded_dirs)
580
+ eval_dataset_files = [f for f in eval_dataset_files if "test" not in f]
581
+
582
+ with open(os.path.join(script_dir, 'input_composition_dict.json'), 'w') as fp:
583
+ json.dump(composition_dict, fp)
584
+ print(composition_dict)
585
+ output_composition_dict_filepath = os.path.join(script_dir, 'llm_judge_output_composition_dict.json')
586
+
587
+ # Calculate regular metrics
588
+ output_composition_dict = metric_calculation_loop(composition_dict, dataset_dir, output_composition_dict_filepath)
589
+ print("Output composition dict: ", pretty_json(output_composition_dict))
590
+ # print("complexity_distribution: ", pretty_json(complexity_distribution))
591
+
592
+ with open(output_composition_dict_filepath, 'w') as fp:
593
+ json.dump(output_composition_dict, fp)
594
+
595
+ # with open(os.path.join(script_dir, 'complexity_distribution.json'), 'w') as fp:
596
+ # json.dump(complexity_distribution, fp)
597
+
598
+ # Calculate pass@k metric:
599
+ # print(metric_calculation_loop(composition_dict, pass_k_parameters))
600
+
601
+ # Display number of rows for each complexity level:
602
+
603
+ if __name__ == "__main__":
604
+ main()
human_reference_dataset/iac-eval/evaluation/misc/ablation-multiple-sample/ablation-multiple-sample.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Assumption: potentially multiple files within the same eval folder (e.g.,results-for-iac-eval (backup)/standard/codellama-7b/george), where each file must contains n (or more) number of evaluation passes
2
+ # Task: combines all "output" related columns and combines them into one single dataframe, saving it to a new folder within pass_k_calculation/combined_eval_dataset/ with a folder layout of (pass_k_calculation/combined_eval_dataset/standard/codellama-7b/george/), then passes through each file and calculates pass@k metrics for various k assuming some fixed N. And constructs an output_composition_dict.json similar to that used in ablation/
3
+ import csv
4
+ import pandas as pd
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ from openai import AzureOpenAI
9
+ import pandas as pd
10
+ import json
11
+ import subprocess
12
+ import copy
13
+ from io import StringIO
14
+ import re
15
+ import sys
16
+ import math
17
+ import click
18
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
19
+ import eval
20
+ import numpy as np
21
+ import metrics
22
+
23
+ DELIMITERS = ["```hcl", "```json", "```HCL", "```Terraform", "```terraform", "```"] # ``` needs to be in the end, as it is a final "else" case
24
+
25
+ LOG_FILE = "logs/eval-repair.log"
26
+
27
+ class CustomFormatter(logging.Formatter):
28
+ # https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
29
+ grey = "\x1b[38;20m"
30
+ cyan = "\x1b[36;20m"
31
+ blue = "\x1b[34:20m"
32
+ yellow = "\x1b[33;20m"
33
+ red = "\x1b[31;20m"
34
+ bold_red = "\x1b[31;1m"
35
+ reset = "\x1b[0m"
36
+ format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
37
+
38
+ FORMATS = {
39
+ logging.DEBUG: cyan + format + reset,
40
+ logging.INFO: blue + format + reset,
41
+ logging.WARNING: yellow + format + reset,
42
+ logging.ERROR: red + format + reset,
43
+ logging.CRITICAL: bold_red + format + reset
44
+ }
45
+
46
+ def format(self, record):
47
+ log_fmt = self.FORMATS.get(record.levelno)
48
+ formatter = logging.Formatter(log_fmt)
49
+ return formatter.format(record)
50
+
51
+ logger = logging.getLogger("iac-eval-repair")
52
+ logger.setLevel(logging.DEBUG)
53
+ #Setup File handler: https://stackoverflow.com/a/24507130/13336187
54
+ file_handler = logging.FileHandler(LOG_FILE)
55
+ file_handler.setFormatter(CustomFormatter())
56
+ file_handler.setLevel(logging.DEBUG)
57
+ #Setup Stream Handler (i.e. console)
58
+ ch = logging.StreamHandler()
59
+ ch.setLevel(logging.DEBUG)
60
+ ch.setFormatter(CustomFormatter())
61
+ # Log to both file and console:
62
+ logger.addHandler(ch)
63
+ logger.addHandler(file_handler)
64
+
65
+ def pretty_json(obj):
66
+ return json.dumps(obj, indent=4, default=str)
67
+
68
+ def estimator(n: int, c: int, k: int) -> float:
69
+ """
70
+ Calculates 1 - comb(n - c, k) / comb(n, k).
71
+ """
72
+ if n - c < k:
73
+ return 1.0
74
+ return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
75
+
76
+ def make_column_names_unique(df):
77
+ for i in range(2): # repeat twice, since after the first time we may still have duplicates: e.g., if #0.1 already exists, and in the initial run we have duplicate #0
78
+ cols = pd.Series(df.columns)
79
+ for dup in cols[cols.duplicated()].unique():
80
+ cols[cols[cols == dup].index.values.tolist()] = [dup + '.' + str(i) if i != 0 else dup for i in range(sum(cols == dup))]
81
+ df.columns = cols
82
+ # print(cols.tolist())
83
+ # while True:
84
+ # x=1
85
+ return df
86
+
87
+ def fix_duplicate_columns(dest_file_path):
88
+ """
89
+ Deduplicated dataframe is returned to the user. dest_file_path is not overwritten.
90
+ """
91
+ df = pd.read_csv(dest_file_path, header=None)
92
+ new_header = df.iloc[0]
93
+ df = df[1:]
94
+ df.columns = new_header
95
+ df.reset_index(drop=True, inplace=True)
96
+
97
+ if not df.columns.is_unique: # First check if there are duplicate columns:
98
+ df = make_column_names_unique(df)
99
+ logger.info(f"Evaluation file {dest_file_path} had duplicate columns, deduplicated them. evaluation file not overwritten.")
100
+ return df
101
+
102
+ def list_all_subdirectories(composition_dict, data_dir, excluded_dirs, strats=["multi-turn", "RAG", "COT", "FSP"]):
103
+ # onlyfiles = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) if dirpath not in excluded_dirs in os.walk(data_dir) for f in filenames]
104
+ onlyfiles = []
105
+ for dirpath, dirnames, filenames in os.walk(data_dir):
106
+ # print(dirpath)
107
+ skip_dirname = False
108
+ # if "standard" in dirpath:
109
+ # print(dirpath)
110
+ for dir1 in excluded_dirs:
111
+ if dir1 in dirpath:
112
+ skip_dirname = True
113
+
114
+ if not skip_dirname:
115
+ for f in filenames:
116
+ skip_file = False
117
+ for exc in excluded_dirs:
118
+ if exc in f:
119
+ skip_file = True
120
+ if not skip_file:
121
+ onlyfiles.append(os.path.join(dirpath, f))
122
+
123
+ # onlyfiles = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk(data_dir) for f in filenames]
124
+ # print(onlyfiles)
125
+ onlyfilescsv = [f for f in onlyfiles if f.endswith(".csv")]
126
+
127
+ # composition_dict = {
128
+ # "gpt4": {
129
+ # "COT": {
130
+ # "weijun": [],
131
+
132
+ # Append to composition dict:
133
+ for file1 in onlyfilescsv:
134
+ included = False
135
+ is_standard = True
136
+ for i in strats:
137
+ if i in file1:
138
+ is_standard = False
139
+
140
+ for model, model_dict in composition_dict.items():
141
+ for strat, student_dict in model_dict.items():
142
+ if is_standard:
143
+ if strat != "Standard":
144
+ continue
145
+ for student, dataset_list in student_dict.items():
146
+ is_file = False
147
+ if is_standard:
148
+ if student in file1 and model in file1:
149
+ is_file = True
150
+ else:
151
+ if student in file1 and strat in file1 and model in file1:
152
+ is_file = True
153
+ if is_file:
154
+ if not included:
155
+ composition_dict[model][strat][student].append(file1)
156
+ included = True
157
+ else:
158
+ print("WARNING: This file attempted to be included multiple times: ", file1)
159
+ if not included:
160
+ print("WARNING: This file was excluded: ", file1)
161
+
162
+ return onlyfilescsv, composition_dict
163
+
164
+ def create_new_dirs_for_metric(new_base_difficulty_dir, base_dataset_files):
165
+ os.makedirs(new_base_difficulty_dir, exist_ok=True)
166
+ for file in base_dataset_files:
167
+ containing_folder = os.path.basename(os.path.dirname(file)) # e.g., weijun
168
+ filename = os.path.basename(file) # e.g., plain-dataset.csv
169
+ # create the directory if it does not exist
170
+ new_dir_path = os.path.join(new_base_difficulty_dir, containing_folder)
171
+ # print(new_dir_path)
172
+ os.makedirs(new_dir_path, exist_ok=True)
173
+
174
+ def metric_calculation_loop(composition_dict, dataset_dir, output_composition_dict_filepath, pass_k_parameters):
175
+
176
+ """
177
+ NOTE: pass@k calculation is limited to standard only for now.
178
+ NOTE: if pass_k_parameters is not None, then we will only calculate pass@k scores, and for standard only.
179
+
180
+ pass_k_parameters format example: {
181
+ "n" = 5,
182
+ "k" = [1,2,5],
183
+ }
184
+ Output format example (added in place to composition_dict): {
185
+ "gpt4": {
186
+ "Standard": {
187
+ ..., # whatever that is already in composition_dict
188
+
189
+ "iac_eval_accuracy": 0.3,
190
+ "pass@k" : { # iac-eval
191
+ "n": 5 # just for record
192
+ "1": 0.5,
193
+ "2": 0.6,
194
+ "5": 0.7,
195
+ },
196
+ "pass@k-tf-plan" : {
197
+ "n": 5 # just for record
198
+ "1": 0.5,
199
+ "2": 0.6,
200
+ "5": 0.7,
201
+ },
202
+ },
203
+ "COT": ...
204
+ },
205
+ "gpt3.5": {
206
+ ...
207
+ },
208
+ ...
209
+ }
210
+ """
211
+
212
+ output_composition_dict = copy.deepcopy(composition_dict) # https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python
213
+
214
+ for model, model_dict in composition_dict.items():
215
+ for strat, student_dict in model_dict.items():
216
+
217
+ pass_k_scores = {}
218
+ pass_k_scores_tf_plan = {}
219
+ for i in pass_k_parameters["k"]:
220
+ pass_k_scores[i] = {
221
+ "score_now": 0,
222
+ "num_rows": 0
223
+ }
224
+ pass_k_scores_tf_plan[i] = {
225
+ "score_now": 0,
226
+ "num_rows": 0
227
+ }
228
+ # pass_k_score_now = 0
229
+ # num_rows = 0
230
+
231
+ passed_once = False
232
+
233
+ iac_eval_complexity_accuracy = {
234
+ "1": {
235
+ "num_success_both": 0,
236
+ "num_rows": 0,
237
+ },
238
+ "2": {
239
+ "num_success_both": 0,
240
+ "num_rows": 0,
241
+ },
242
+ "3": {
243
+ "num_success_both": 0,
244
+ "num_rows": 0,
245
+ },
246
+ "4": {
247
+ "num_success_both": 0,
248
+ "num_rows": 0,
249
+ },
250
+ "5": {
251
+ "num_success_both": 0,
252
+ "num_rows": 0,
253
+ },
254
+ "6": {
255
+ "num_success_both": 0,
256
+ "num_rows": 0,
257
+ }
258
+ }
259
+
260
+ for student, dataset_list in student_dict.items():
261
+ # n_total = 0 # number of trials that this student has been evaluated for. Used for pass@k's n parameter
262
+ for file1 in dataset_list:
263
+ # Go through each row
264
+ df = pd.read_csv(file1) # this is now redundant since the next line also reads the file
265
+ df = fix_duplicate_columns(file1)
266
+ print(f"Begin calc metrics for dataset {file1}")
267
+
268
+ # iterate through each row
269
+ for index, row in df.iterrows():
270
+
271
+ passed_once = True
272
+ # find specific column
273
+ # print(index)
274
+ # while True:
275
+ # x=1
276
+
277
+ if isinstance(row["Prompt"], float):
278
+ continue
279
+
280
+ # dataset_df, dataset_row = extract_dataset_row(row, index, df, dataset_dir, file1) # extract the corresponding row from the "data" dataset file
281
+
282
+ # complexity = difficulty_retrieval(dataset_row)
283
+ # Check all samples: Loop through columns whose names match the substring
284
+ num_samples = 0
285
+ num_correct = 0
286
+ num_tf_plan_correct = 0
287
+ for column in df.filter(like="LLM Output #"):
288
+ num_samples += 1
289
+ # print(f"Processing column: {column}")
290
+ sample_count = column.split("#")[1]
291
+ plannable = row["LLM Plannable? #{}".format(sample_count)]
292
+ correct = row["LLM Correct? #{}".format(sample_count)]
293
+ if plannable == "True" or plannable == True or plannable == "TRUE": # needed these extra conditions because fixing duplicate columns causes for example TRUE which would normally be evaluated into the boolean True, to be evaluated as a string TRUE instead..
294
+ num_tf_plan_correct += 1
295
+ if correct == "Success":
296
+ num_correct += 1
297
+ # iac_eval_complexity_accuracy[complexity]["num_success_both"] += 1
298
+
299
+ if num_samples == pass_k_parameters["n"]: # only evaluate up till n samples, even if there are more
300
+ break
301
+
302
+ if "Wizard" in file1:
303
+ print(num_correct)
304
+ # if "Wizard" in file1:
305
+ # while True:
306
+ # x=1
307
+
308
+ assert num_samples == pass_k_parameters["n"] # prereq: must have at least n samples
309
+ for k, attrs in pass_k_scores.items():
310
+ attrs["score_now"] += estimator(
311
+ pass_k_parameters["n"], num_correct, k
312
+ )
313
+ attrs["num_rows"] += 1
314
+ for k, attrs in pass_k_scores_tf_plan.items():
315
+ attrs["score_now"] += estimator(
316
+ pass_k_parameters["n"], num_tf_plan_correct, k
317
+ )
318
+ attrs["num_rows"] += 1
319
+
320
+ print(f"Finished calc metrics for dataset {file1}")
321
+
322
+ if not passed_once:
323
+ # print(strat)
324
+ # while True:
325
+ # x=1
326
+ continue
327
+
328
+ # Calculate pass@k scores
329
+ output_composition_dict[model][strat]["pass@k"] = {
330
+ "n": str(pass_k_parameters["n"])
331
+ }
332
+ output_composition_dict[model][strat]["pass@k-tf-plan"] = {
333
+ "n": str(pass_k_parameters["n"])
334
+ }
335
+ for k, attrs in pass_k_scores.items():
336
+ output_composition_dict[model][strat]["pass@k"][k] = str(attrs["score_now"]/attrs["num_rows"])
337
+ for k, attrs in pass_k_scores_tf_plan.items():
338
+ output_composition_dict[model][strat]["pass@k-tf-plan"][k] = str(attrs["score_now"]/attrs["num_rows"])
339
+
340
+ # Copy over the IAC eval accuracy from the ablation output composition dict: (for plotting purposes)
341
+ with open(os.path.join(os.path.dirname(output_composition_dict_filepath), "../ablation", "output_composition_dict.json"), 'r') as fp:
342
+ ablation_output_composition_dict = json.load(fp)
343
+ output_composition_dict[model][strat]["iac_eval_accuracy"] = str(ablation_output_composition_dict[model][strat]["iac_eval_accuracy"])
344
+
345
+ with open(output_composition_dict_filepath, 'w') as fp: # incremental updates
346
+ json.dump(output_composition_dict, fp)
347
+
348
+ return output_composition_dict
349
+
350
+ def extract_dataset_row(eval_row, eval_index, eval_df, dataset_dir, eval_filename, strats=["multi-turn", "RAG", "COT", "FSP"]):
351
+ """
352
+ Example eval_filename: '/home/ubuntu/autoiac-tasks/evaluation/misc/ablation/../../../results-for-iac-eval (backup)/multi-turn/codellama-34b/george/evaluation-dataset-for-plain-dataset-george-existing-multi-turn.csv'
353
+ """
354
+
355
+ # Extract corresponding "data" dataset file name:
356
+ file_stem = Path(eval_filename).stem # https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
357
+ file_stem = file_stem.split("evaluation-dataset-for-")[1]
358
+ filename = ""
359
+ for i in strats:
360
+ if i in file_stem:
361
+ filename = file_stem.split("-{}".format(i))[0] + ".csv"
362
+ if filename == "":
363
+ filename = file_stem + ".csv"
364
+
365
+ filename = "difficulty-included-" + filename
366
+
367
+ containing_folder = os.path.basename(os.path.dirname(eval_filename)) # e.g., weijun
368
+ dataset_filename = os.path.join(dataset_dir, containing_folder, filename)
369
+
370
+ # Access dataset file and extract required row
371
+ df = pd.read_csv(dataset_filename, header=None)
372
+
373
+ # set the third row as the header
374
+ new_header = df.iloc[0]
375
+ df = df[1:]
376
+ df.columns = new_header
377
+ # # reset the index of the DataFrame
378
+ df.reset_index(drop=True, inplace=True)
379
+
380
+ # print(df.at[eval_index, "Prompt"])
381
+ # while True:
382
+ # x=1
383
+
384
+ # print(df)
385
+
386
+ # assert df.at[eval_index, "Prompt"] == eval_row["Prompt"] # add this back in as needed. Removed for now since I might have updated some dataset rows after some eval was performed on the old version of the dataset..
387
+
388
+ return df, df.iloc[eval_index]
389
+
390
+ def difficulty_retrieval(row, difficulty_header="Calculated Complexity"):
391
+ prompt = row["Prompt"]
392
+ if isinstance(prompt, float):
393
+ if math.isnan(prompt):
394
+ return
395
+ reference = row["Desired output"]
396
+ policy = row["Rego intent"]
397
+
398
+ print("Prompt:", prompt)
399
+
400
+ return row[difficulty_header]
401
+
402
+ def difficulty_calculation(row, df, index, new_difficulty_headers=["Calculated Complexity"]):
403
+ prompt = row["Prompt"]
404
+ if isinstance(prompt, float):
405
+ if math.isnan(prompt):
406
+ return
407
+ reference = row["Desired output"]
408
+ policy = row["Rego intent"]
409
+
410
+ print("Prompt:", prompt)
411
+
412
+ complexity_level = calc_complexity(reference, prompt)
413
+ # ambiguity_level = calc_ambiguity(policy, prompt)
414
+ # print(complexity_level, ambiguity_level)
415
+ # print("Complexity level: ", complexity_level)
416
+ # print("Ambiguity level: ", ambiguity_level)
417
+
418
+ for header in new_difficulty_headers:
419
+ if "Complexity" in header:
420
+ df.at[index, header] = complexity_level
421
+ # elif "Ambiguity" in header:
422
+ # df.at[index, header] = ambiguity_level
423
+
424
+ return complexity_level
425
+
426
+ def calc_complexity(reference, prompt):
427
+ """
428
+ Calculate complexity based on LOC, num resources, and number of interconnections.
429
+ """
430
+ # Calculate LOC:
431
+ LOC = sum(not line.isspace() for line in StringIO(reference))
432
+ # print("LOC", LOC)
433
+
434
+ # Calculate number of resources:
435
+ # Count the number of occurences of the word "resource" in the reference string
436
+ num_resources = reference.count("resource")
437
+ # print("num_resources", num_resources)
438
+
439
+ # Calculate number of interconnections:
440
+ write_to_terraform(reference)
441
+ # run terraform plan and capture the output and errors
442
+ plan_file = "plan.out"
443
+ terraform_dir = "./misc/ablation/terraform_config"
444
+ output_json_file = "plan.json"
445
+ output_json_filepath = os.path.join(terraform_dir, output_json_file)
446
+ generate_terraform_plan_json(prompt, terraform_dir, plan_file, output_json_file)
447
+ # read the json file
448
+ # print("about to read json..")
449
+ with open(output_json_filepath, "r") as json_file:
450
+ data = json.load(json_file)
451
+ # extract the number of interconnections from the json file
452
+ config_graph = data["configuration"]["root_module"]["resources"]
453
+ references_list = list(findkeys(config_graph, "references")) # just a list with the word "references" repeated
454
+ # print(references_list)
455
+ num_interconnections = len(references_list)
456
+ # print("num_interconnections", num_interconnections)
457
+ # Determine complexity:
458
+ return get_complexity_level(LOC, num_resources, num_interconnections)
459
+
460
+ def get_complexity_level(LOC, num_resources, num_interconnections):
461
+ if LOC < 10 and num_resources < 2 and num_interconnections < 2:
462
+ return "1"
463
+ if LOC < 20 and num_resources < 4 and num_interconnections < 4:
464
+ return "2"
465
+ if LOC < 40 and num_resources < 6 and num_interconnections < 6:
466
+ return "3"
467
+ if LOC < 60 and num_resources < 8 and num_interconnections < 8:
468
+ return "4"
469
+ if LOC < 80 and num_resources < 10 and num_interconnections < 10:
470
+ return "5"
471
+ if LOC >= 80 or num_resources >= 10 or num_interconnections >= 10:
472
+ return "6"
473
+
474
+ def findkeys(node, kv):
475
+ # Modified from: https://stackoverflow.com/a/19871956/13336187
476
+ if isinstance(node, list):
477
+ for i in node:
478
+ for x in findkeys(i, kv):
479
+ yield x
480
+ elif isinstance(node, dict):
481
+ if kv in node:
482
+ yield kv
483
+ for j in node.values():
484
+ for x in findkeys(j, kv):
485
+ yield x
486
+
487
+ # print(list(findkeys(d, 'id')))
488
+
489
+ def write_to_terraform(result, terraform_dir="./misc/ablation/terraform_config"):
490
+ # define the path to the main.tf file
491
+ terraform_file_path = terraform_dir + "/metric-measurement-main.tf"
492
+ # open the file in write mode ('w') and write the result to it
493
+ # print("CWD", os.getcwd())
494
+ # print("CWD: {}".format(os.getcwd()))
495
+ with open(terraform_file_path, "w+", encoding="utf-8", errors="ignore") as file:
496
+ file.write(result)
497
+ # print(f"Updated main.tf at {terraform_file_path}")
498
+ # print(f"Updated main.tf at {terraform_file_path}")
499
+
500
+ def generate_terraform_plan_json(prompt, terraform_dir="./misc/ablation/terraform_config", plan_file="plan.out", output_json_file="plan.json"):
501
+ cwd = os.getcwd()
502
+ # change to the Terraform directory
503
+ os.chdir(terraform_dir)
504
+ # run init before plan
505
+ init_result = subprocess.run(["terraform", "init"], capture_output=True, text=True)
506
+
507
+ # run 'terraform plan'
508
+ # result = subprocess.run(["terraform", "plan"], capture_output=True, text=True)
509
+
510
+ result_returned = False
511
+ # generate Terraform plan with the -no-color flag
512
+ for i in range(2): # try twice
513
+ try:
514
+ result = subprocess.run(
515
+ ["terraform", "plan", "-out", plan_file, "-no-color"], capture_output=True, text=True, timeout=300 # 5 minutes timeout (assume failed if timeout)
516
+ )
517
+
518
+ with open(
519
+ output_json_file, "w", encoding="utf-8", errors="ignore"
520
+ ) as json_file:
521
+ show_result = subprocess.run(
522
+ ["terraform", "show", "-json", plan_file], check=True, stdout=json_file
523
+ )
524
+
525
+ result_returned = True
526
+ break
527
+ except Exception as e:
528
+ print("Error occurred for prompt \"{}\": {}".format(prompt, e))
529
+
530
+ # Return to parent directory
531
+ os.chdir(cwd)
532
+
533
+ if result_returned == False:
534
+ return "Plan timed-out. No output", "Plan timed-out. No error", False
535
+
536
+ @click.command()
537
+ @click.option(
538
+ "--samples",
539
+ "-n",
540
+ "samples",
541
+ type=int,
542
+ help="Number of samples per task.",
543
+ default=20,
544
+ )
545
+ def main(samples: int):
546
+ # Find dataset files:
547
+ script_dir = os.path.dirname(os.path.abspath(__file__))
548
+ eval_dataset_dir = os.path.join(script_dir, "../..", "results")
549
+ dataset_dir = os.path.join(script_dir, "../complete-dataset-measurement/complete-dataset")
550
+ # print()
551
+ excluded_dirs = ["llm-judge-evaluation-metric", "pass", # skip filenames containing "pass". will merge them into a regular file once done with eval..
552
+ "multi-turn", "RAG", "COT", "FSP"] # also skip these for now since we don't have the data: just add these back in once the data is ready and we're good to go
553
+ composition_dict = {
554
+ "gpt4": {
555
+ "COT": {
556
+ "complete": [],
557
+ },
558
+ "FSP": {
559
+ "complete": [],
560
+ },
561
+ "multi-turn": {
562
+ "complete": [],
563
+ },
564
+ "RAG": {
565
+ "complete": [],
566
+ },
567
+ "Standard": {
568
+ "complete": [],
569
+ },
570
+ },
571
+ "gpt3.5": {
572
+ "COT": {
573
+ "complete": [],
574
+ },
575
+ "FSP": {
576
+ "complete": [],
577
+ },
578
+ "multi-turn": {
579
+ "complete": [],
580
+ },
581
+ "RAG": {
582
+ "complete": [],
583
+ },
584
+ "Standard": {
585
+ "complete": [],
586
+ },
587
+ },
588
+ "gemini-1.0-pro": {
589
+ "COT": {
590
+ "complete": [],
591
+ },
592
+ "FSP": {
593
+ "complete": [],
594
+ },
595
+ "multi-turn": {
596
+ "complete": [],
597
+ },
598
+ "RAG": {
599
+ "complete": [],
600
+ },
601
+ "Standard": {
602
+ "complete": [],
603
+ },
604
+ },
605
+ "codellama-34b": {
606
+ "COT": {
607
+ "complete": [],
608
+ },
609
+ "FSP": {
610
+ "complete": [],
611
+ },
612
+ "multi-turn": {
613
+ "complete": [],
614
+ },
615
+ "RAG": {
616
+ "complete": [],
617
+ },
618
+ "Standard": {
619
+ "complete": [],
620
+ },
621
+ },
622
+ "codellama-13b": {
623
+ "COT": {
624
+ "complete": [],
625
+ },
626
+ "FSP": {
627
+ "complete": [],
628
+ },
629
+ "multi-turn": {
630
+ "complete": [],
631
+ },
632
+ "RAG": {
633
+ "complete": [],
634
+ },
635
+ "Standard": {
636
+ "complete": [],
637
+ },
638
+ },
639
+ "codellama-7b": {
640
+ "COT": {
641
+ "complete": [],
642
+ },
643
+ "FSP": {
644
+ "complete": [],
645
+ },
646
+ "multi-turn": {
647
+ "complete": [],
648
+ },
649
+ "RAG": {
650
+ "complete": [],
651
+ },
652
+ "Standard": {
653
+ "complete": [],
654
+ },
655
+ },
656
+ "Magicoder_S_CL_7B": {
657
+ "COT": {
658
+ "complete": [],
659
+ },
660
+ "FSP": {
661
+ "complete": [],
662
+ },
663
+ "multi-turn": {
664
+ "complete": [],
665
+ },
666
+ "RAG": {
667
+ "complete": [],
668
+ },
669
+ "Standard": {
670
+ "complete": [],
671
+ },
672
+ },
673
+ "Wizardcoder33b": {
674
+ "COT": {
675
+ "complete": [],
676
+ },
677
+ "FSP": {
678
+ "complete": [],
679
+ },
680
+ "multi-turn": {
681
+ "complete": [],
682
+ },
683
+ "RAG": {
684
+ "complete": [],
685
+ },
686
+ "Standard": {
687
+ "complete": [],
688
+ },
689
+ }
690
+ }
691
+ eval_dataset_files, composition_dict = list_all_subdirectories(composition_dict, eval_dataset_dir, excluded_dirs)
692
+ eval_dataset_files = [f for f in eval_dataset_files if "test" not in f]
693
+ # print(eval_dataset_files)
694
+
695
+ with open(os.path.join(script_dir, 'input_composition_dict.json'), 'w') as fp:
696
+ json.dump(composition_dict, fp)
697
+
698
+ # while True:
699
+ # x=1
700
+
701
+ print(composition_dict)
702
+ # metrics_included_dataset_dir = script_dir + "/ablation-dataset"
703
+ # create_new_dirs_for_metric(metrics_included_dataset_dir, dataset_files)
704
+ # dst_filenames = copy_csv_to_metric(dataset_files, difficulty_included_dataset_dir)
705
+ # # print(dst_filenames)
706
+
707
+ pass_k_parameters = {
708
+ "n": samples,
709
+ "k": [x for x in range(1, samples+1)]
710
+ }
711
+
712
+ output_composition_dict_filepath = os.path.join(script_dir, 'pass-k-output_composition_dict.json')
713
+
714
+ # Calculate regular metrics
715
+ output_composition_dict = metric_calculation_loop(composition_dict, dataset_dir, output_composition_dict_filepath, pass_k_parameters)
716
+ print("Output composition dict: ", pretty_json(output_composition_dict))
717
+ # print("complexity_distribution: ", pretty_json(complexity_distribution))
718
+
719
+ with open(output_composition_dict_filepath, 'w') as fp:
720
+ json.dump(output_composition_dict, fp)
721
+
722
+ # with open(os.path.join(script_dir, 'complexity_distribution.json'), 'w') as fp:
723
+ # json.dump(complexity_distribution, fp)
724
+
725
+ # Calculate pass@k metric:
726
+ # print(metric_calculation_loop(composition_dict, pass_k_parameters))
727
+
728
+ # Display number of rows for each complexity level:
729
+
730
+ if __name__ == "__main__":
731
+ main()
human_reference_dataset/iac-eval/evaluation/misc/ablation/ablation-iac-eval-pipeline.py ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Assumption: single file for each evaluated dataset. (e.g., no -pass5 and -pass1 in the same folder.)
2
+ import csv
3
+ import pandas as pd
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+ from openai import AzureOpenAI
8
+ import pandas as pd
9
+ import json
10
+ import math
11
+ import subprocess
12
+ import copy
13
+ from io import StringIO
14
+ import re
15
+ import sys
16
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
17
+ import eval
18
+ import metrics
19
+
20
+ DELIMITERS = ["```hcl", "```json", "```HCL", "```Terraform", "```terraform", "```"] # ``` needs to be in the end, as it is a final "else" case
21
+
22
+ LOG_FILE = "logs/eval-repair.log"
23
+
24
+ class CustomFormatter(logging.Formatter):
25
+ # https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
26
+ grey = "\x1b[38;20m"
27
+ cyan = "\x1b[36;20m"
28
+ blue = "\x1b[34:20m"
29
+ yellow = "\x1b[33;20m"
30
+ red = "\x1b[31;20m"
31
+ bold_red = "\x1b[31;1m"
32
+ reset = "\x1b[0m"
33
+ format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
34
+
35
+ FORMATS = {
36
+ logging.DEBUG: cyan + format + reset,
37
+ logging.INFO: blue + format + reset,
38
+ logging.WARNING: yellow + format + reset,
39
+ logging.ERROR: red + format + reset,
40
+ logging.CRITICAL: bold_red + format + reset
41
+ }
42
+
43
+ def format(self, record):
44
+ log_fmt = self.FORMATS.get(record.levelno)
45
+ formatter = logging.Formatter(log_fmt)
46
+ return formatter.format(record)
47
+
48
+ logger = logging.getLogger("iac-eval-repair")
49
+ logger.setLevel(logging.DEBUG)
50
+ #Setup File handler: https://stackoverflow.com/a/24507130/13336187
51
+ file_handler = logging.FileHandler(LOG_FILE)
52
+ file_handler.setFormatter(CustomFormatter())
53
+ file_handler.setLevel(logging.DEBUG)
54
+ #Setup Stream Handler (i.e. console)
55
+ ch = logging.StreamHandler()
56
+ ch.setLevel(logging.DEBUG)
57
+ ch.setFormatter(CustomFormatter())
58
+ # Log to both file and console:
59
+ logger.addHandler(ch)
60
+ logger.addHandler(file_handler)
61
+
62
+ def pretty_json(obj):
63
+ return json.dumps(obj, sort_keys=True, indent=4, default=str)
64
+
65
+ def estimator(n: int, c: int, k: int) -> float:
66
+ """
67
+ Calculates 1 - comb(n - c, k) / comb(n, k).
68
+ """
69
+ if n - c < k:
70
+ return 1.0
71
+ return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
72
+
73
+ def list_all_subdirectories(composition_dict, data_dir, excluded_dirs, strats=["multi-turn", "RAG", "COT", "FSP"]):
74
+ # onlyfiles = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) if dirpath not in excluded_dirs in os.walk(data_dir) for f in filenames]
75
+ onlyfiles = []
76
+ for dirpath, dirnames, filenames in os.walk(data_dir):
77
+ # print(dirpath)
78
+ skip_dirname = False
79
+ for dir1 in excluded_dirs:
80
+ if dir1 in dirpath:
81
+ skip_dirname = True
82
+
83
+ if not skip_dirname:
84
+ for f in filenames:
85
+ skip_file = False
86
+ for exc in excluded_dirs:
87
+ if exc in f:
88
+ skip_file = True
89
+ if not skip_file:
90
+ onlyfiles.append(os.path.join(dirpath, f))
91
+
92
+ # onlyfiles = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk(data_dir) for f in filenames]
93
+ # print(onlyfiles)
94
+ onlyfilescsv = [f for f in onlyfiles if f.endswith(".csv")]
95
+
96
+ # composition_dict = {
97
+ # "gpt4": {
98
+ # "COT": {
99
+ # "weijun": [],
100
+
101
+ # Append to composition dict:
102
+ for file1 in onlyfilescsv:
103
+ included = False
104
+ is_standard = True
105
+ for i in strats:
106
+ if i in file1:
107
+ is_standard = False
108
+
109
+ for model, model_dict in composition_dict.items():
110
+ for strat, student_dict in model_dict.items():
111
+ if is_standard:
112
+ if strat != "Standard":
113
+ continue
114
+ for student, dataset_list in student_dict.items():
115
+ is_file = False
116
+ if is_standard:
117
+ if student in file1 and model in file1:
118
+ is_file = True
119
+ else:
120
+ if student in file1 and strat in file1 and model in file1:
121
+ is_file = True
122
+ if is_file:
123
+ if not included:
124
+ composition_dict[model][strat][student].append(file1)
125
+ included = True
126
+ else:
127
+ print("WARNING: This file attempted to be included multiple times: ", file1)
128
+ if not included:
129
+ print("WARNING: This file was excluded: ", file1)
130
+
131
+ return onlyfilescsv, composition_dict
132
+
133
+ def create_new_dirs_for_metric(new_base_difficulty_dir, base_dataset_files):
134
+ os.makedirs(new_base_difficulty_dir, exist_ok=True)
135
+ for file in base_dataset_files:
136
+ containing_folder = os.path.basename(os.path.dirname(file)) # e.g., weijun
137
+ filename = os.path.basename(file) # e.g., plain-dataset.csv
138
+ # create the directory if it does not exist
139
+ new_dir_path = os.path.join(new_base_difficulty_dir, containing_folder)
140
+ # print(new_dir_path)
141
+ os.makedirs(new_dir_path, exist_ok=True)
142
+
143
+ def metric_calculation_loop(composition_dict, dataset_dir, output_composition_dict_filepath, pass_k_parameters=None):
144
+
145
+ """
146
+ NOTE: pass@k calculation is limited to standard only for now.
147
+ NOTE: if pass_k_parameters is not None, then we will only calculate pass@k scores, and for standard only.
148
+
149
+ pass_k_parameters format example: {
150
+ "n" = 5,
151
+ "k" = [1,2,5],
152
+ }
153
+ Output format example (added in place to composition_dict): {
154
+ "gpt4": {
155
+ "Standard": {
156
+ ..., # whatever that is already in composition_dict
157
+
158
+ "iac_eval_accuracy": 0.3,
159
+ "tf_plan_only_accuracy": 0.4
160
+ "iac_eval_complexity_accuracy" : {
161
+ "1": 0,
162
+ "2": 0,
163
+ "3": 0,
164
+ "4": 0,
165
+ "5": 0,
166
+ "6": 0,
167
+ },
168
+ "pass@k" : {
169
+ "n": 5 # just for record
170
+ "1": 0.5,
171
+ "2": 0.6,
172
+ "5": 0.7,
173
+ }
174
+ "bleu_accuracy": 0.8,
175
+ "exact_match_accuracy": 0.5
176
+ # will add this in later once patch up llm-judge-eval.py:
177
+ # "llm-judge": {
178
+ # "accuracy": 0.8,
179
+ # "precision": 0.5,
180
+ # "recall": 0.3
181
+ # }
182
+ },
183
+ "COT": ...
184
+ },
185
+ "gpt3.5": {
186
+ ...
187
+ },
188
+ ...
189
+ }
190
+ """
191
+
192
+ output_composition_dict = copy.deepcopy(composition_dict) # https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python
193
+
194
+ # complexity_distribution = {
195
+ # "level-1": 0,
196
+ # "level-2": 0,
197
+ # "level-3": 0,
198
+ # "level-4": 0,
199
+ # "level-5": 0,
200
+ # "level-6": 0,
201
+ # }
202
+
203
+ for model, model_dict in composition_dict.items():
204
+ for strat, student_dict in model_dict.items():
205
+ if strat != "Standard":
206
+ continue
207
+ num_success_both = 0 # pass iac_eval pipeline correctly
208
+ num_rows = 0
209
+ num_plan_success = 0
210
+ bleu_score_total = 0
211
+ bleu_score_total_correct = 0
212
+ bleu_score_total_incorrect = 0
213
+ exact_match_count = 0
214
+ false_positive_count = 0
215
+ false_negative_count = 0
216
+
217
+ codebert_metrics_total = {
218
+ "precision": 0,
219
+ "recall": 0,
220
+ "f1": 0,
221
+ "f3": 0,
222
+ "f1-correct": 0,
223
+ "f1-incorrect": 0,
224
+ }
225
+
226
+ passed_once = False
227
+
228
+ iac_eval_complexity_accuracy = {
229
+ "1": {
230
+ "num_success_both": 0,
231
+ "num_rows": 0,
232
+ },
233
+ "2": {
234
+ "num_success_both": 0,
235
+ "num_rows": 0,
236
+ },
237
+ "3": {
238
+ "num_success_both": 0,
239
+ "num_rows": 0,
240
+ },
241
+ "4": {
242
+ "num_success_both": 0,
243
+ "num_rows": 0,
244
+ },
245
+ "5": {
246
+ "num_success_both": 0,
247
+ "num_rows": 0,
248
+ },
249
+ "6": {
250
+ "num_success_both": 0,
251
+ "num_rows": 0,
252
+ }
253
+ }
254
+
255
+ if strat == "Standard" and pass_k_parameters:
256
+ pass_at_k_scores = {}
257
+ for i in pass_k_parameters:
258
+ pass_at_k_scores[i] = {
259
+ "score_now": 0,
260
+ "num_rows": 0
261
+ }
262
+
263
+ for student, dataset_list in student_dict.items():
264
+ # n_total = 0 # number of trials that this student has been evaluated for. Used for pass@k's n parameter
265
+ for file1 in dataset_list:
266
+ # Go through each row
267
+ df = pd.read_csv(file1)
268
+ print(f"Begin calc metrics for dataset {file1}")
269
+
270
+ # iterate through each row
271
+ for index, row in df.iterrows():
272
+
273
+ if isinstance(row["Prompt"], float):
274
+ if math.isnan(row["Prompt"]):
275
+ continue
276
+
277
+ passed_once = True
278
+ # find specific column
279
+ # print(index)
280
+ # while True:
281
+ # x=1
282
+
283
+ dataset_df, dataset_row = extract_dataset_row(row, index, df, dataset_dir, file1) # extract the corresponding row from the "data" dataset file
284
+
285
+ complexity = difficulty_retrieval(dataset_row)
286
+
287
+ # Calculate pass@k scores.
288
+ if strat == "Standard" and pass_k_parameters:
289
+ num_correct = 0
290
+ columns = df.columns
291
+ n_now = [c for c in columns if "LLM Plannable" in c]
292
+ assert n_now == pass_k_parameters["n"]
293
+ for i in range(n_now):
294
+ if row["LLM Plannable? #{}".format(i)] == True:
295
+ # num_plan_success += 1
296
+ if row["LLM Correct? #{}".format(i)] == "Success":
297
+ num_correct += 1
298
+
299
+ for k, attrs in pass_at_k_scores.items():
300
+ attrs["score_now"] += estimator(
301
+ pass_k_parameters["n"], num_correct, k
302
+ )
303
+ attrs["num_rows"] += 1
304
+
305
+ else: # this includes strat == "Standard" but pass_k_parameters is not provided
306
+ # print(row)
307
+ # if row["LLM Plannable? #0"] != False:
308
+ # while True:
309
+ # x=1
310
+ reference = row["Reference output"]
311
+ try:
312
+ answer, candidate = eval.separate_answer_and_code(row["LLM Output #0"], DELIMITERS)
313
+ except Exception as e:
314
+ s = str(e)
315
+ print(s)
316
+ if "'float' object has no attribute 'split'" in s:
317
+ candidate = ""
318
+ # print(complexity)
319
+ iac_eval_complexity_accuracy[complexity]["num_rows"] += 1
320
+ num_rows += 1
321
+ bleu_score_total += metrics.bleu_score(reference, candidate)
322
+ exact_match_count += 1 if metrics.exact_match(reference, candidate) else 0
323
+
324
+ codebert_metrics = metrics.get_code_bert_score(reference, candidate, row["Prompt"])
325
+ codebert_metrics_total["precision"] += codebert_metrics["precision"]
326
+ codebert_metrics_total["recall"] += codebert_metrics["recall"]
327
+ codebert_metrics_total["f1"] += codebert_metrics["f1"]
328
+ codebert_metrics_total["f3"] += codebert_metrics["f3"]
329
+ is_correct = False
330
+ if row["LLM Plannable? #0"] == True: # we use #0 even if it is possible that a mistake was made somewhere and we evaluated e.g., FSP twice.
331
+ num_plan_success += 1
332
+ print("num_plan_success: ", num_plan_success)
333
+ if row["LLM Correct? #0"] == "Success":
334
+ num_success_both += 1
335
+ is_correct = True
336
+ # while True:
337
+ # x=1
338
+ print("num_success_both: ", num_success_both)
339
+ iac_eval_complexity_accuracy[complexity]["num_success_both"] += 1
340
+
341
+ if is_correct:
342
+ bleu_score_total_correct += metrics.bleu_score(reference, candidate)
343
+ codebert_metrics_total["f1-correct"] += codebert_metrics["f1"]
344
+ else:
345
+ bleu_score_total_incorrect += metrics.bleu_score(reference, candidate)
346
+ codebert_metrics_total["f1-incorrect"] += codebert_metrics["f1"]
347
+
348
+ # complexity_distribution = update_complexity_distribution(complexity, complexity_distribution)
349
+
350
+ # print(f"Complexity distribution now: {complexity_distribution}")
351
+
352
+ # df.to_csv(file1, index=False, encoding="utf-8")
353
+ print(f"Finished calc metrics for dataset {file1}")
354
+
355
+ if not passed_once:
356
+ continue
357
+
358
+ # Calculate pass@k scores
359
+ if strat == "Standard" and pass_k_parameters:
360
+ output_composition_dict[model][strat]["pass@k"] = {
361
+ "n": pass_k_parameters["n"]
362
+ }
363
+ for k, attrs in pass_at_k_scores.items():
364
+ output_composition_dict[model][strat]["pass@k"][k] = attrs["score_now"]/attrs["num_rows"]
365
+
366
+ else: # Calculate metric scores
367
+ output_composition_dict[model][strat]["iac_eval_accuracy"] = num_success_both / num_rows
368
+ output_composition_dict[model][strat]["tf_plan_only_accuracy"] = num_plan_success / num_rows
369
+ output_composition_dict[model][strat]["iac_eval_complexity_accuracy"] = {}
370
+ for level, attrs in iac_eval_complexity_accuracy.items():
371
+ # print("iac_eval_complexity_accuracy: ", iac_eval_complexity_accuracy)
372
+ # print("level: ", level)
373
+ # print("attrs: ", attrs)
374
+ # print("output_composition_dict[model][strat][iac_eval_complexity_accuracy] :", output_composition_dict[model][strat]["iac_eval_complexity_accuracy"])
375
+ # print(output_composition_dict[model][strat]["iac_eval_complexity_accuracy"][level])
376
+ # print(attrs["num_success_both"])
377
+ # print(attrs["num_rows"])
378
+ if attrs["num_rows"] == 0:
379
+ output_composition_dict[model][strat]["iac_eval_complexity_accuracy"][level] = 0
380
+ else:
381
+ output_composition_dict[model][strat]["iac_eval_complexity_accuracy"][level] = attrs["num_success_both"]/attrs["num_rows"]
382
+ output_composition_dict[model][strat]["bleu_accuracy"] = bleu_score_total / num_rows
383
+ if num_success_both == 0:
384
+ output_composition_dict[model][strat]["bleu_accuracy_correct"] = 0
385
+ else:
386
+ output_composition_dict[model][strat]["bleu_accuracy_correct"] = bleu_score_total_correct / num_success_both
387
+ output_composition_dict[model][strat]["bleu_accuracy_incorrect"] = bleu_score_total_incorrect / (num_rows - num_success_both)
388
+ output_composition_dict[model][strat]["exact_match_accuracy"] = exact_match_count / num_rows
389
+ output_composition_dict[model][strat]["codebert_metrics"] = {
390
+ "precision": codebert_metrics_total["precision"] / num_rows,
391
+ "recall": codebert_metrics_total["recall"] / num_rows,
392
+ "f1": codebert_metrics_total["f1"] / num_rows,
393
+ "f3": codebert_metrics_total["f3"] / num_rows,
394
+ "f1-incorrect": codebert_metrics_total["f1-incorrect"] / (num_rows - num_success_both)
395
+ }
396
+ if num_success_both == 0:
397
+ output_composition_dict[model][strat]["codebert_metrics"]["f1-correct"] = 0
398
+ else:
399
+ output_composition_dict[model][strat]["codebert_metrics"]["f1-correct"] = codebert_metrics_total["f1-correct"] / num_success_both
400
+
401
+ with open(output_composition_dict_filepath, 'w') as fp: # incremental updates
402
+ json.dump(output_composition_dict, fp)
403
+
404
+ return output_composition_dict
405
+
406
+ def extract_dataset_row(eval_row, eval_index, eval_df, dataset_dir, eval_filename, strats=["multi-turn", "RAG", "COT", "FSP"]):
407
+ """
408
+ Example eval_filename: '/home/ubuntu/autoiac-tasks/evaluation/misc/ablation/../../../results-for-iac-eval (backup)/multi-turn/codellama-34b/george/evaluation-dataset-for-plain-dataset-george-existing-multi-turn.csv'
409
+ """
410
+
411
+ # Extract corresponding "data" dataset file name:
412
+ file_stem = Path(eval_filename).stem # https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
413
+ file_stem = file_stem.split("evaluation-dataset-for-")[1]
414
+ filename = ""
415
+ for i in strats:
416
+ if i in file_stem:
417
+ filename = file_stem.split("-{}".format(i))[0] + ".csv"
418
+ if filename == "":
419
+ filename = file_stem + ".csv"
420
+
421
+ # filename = "completed-" + filename
422
+
423
+ containing_folder = os.path.basename(os.path.dirname(eval_filename)) # e.g., weijun
424
+ dataset_filename = os.path.join(dataset_dir, containing_folder, filename)
425
+
426
+ # Access dataset file and extract required row
427
+ df = pd.read_csv(dataset_filename, header=None)
428
+
429
+ # set the third row as the header
430
+ new_header = df.iloc[0]
431
+ df = df[1:]
432
+ df.columns = new_header
433
+ # # reset the index of the DataFrame
434
+ df.reset_index(drop=True, inplace=True)
435
+
436
+ # print(df.at[eval_index, "Prompt"])
437
+ # while True:
438
+ # x=1
439
+
440
+ # print(df)
441
+
442
+ # assert df.at[eval_index, "Prompt"] == eval_row["Prompt"] # add this back in as needed. Removed for now since I might have updated some dataset rows after some eval was performed on the old version of the dataset..
443
+
444
+ return df, df.iloc[eval_index]
445
+
446
+ def difficulty_retrieval(row, difficulty_header="Difficulty"):
447
+ prompt = row["Prompt"]
448
+ reference = row["Reference output"]
449
+ policy = row["Rego intent"]
450
+
451
+ print("Prompt:", prompt)
452
+
453
+ return str(int(float(row[difficulty_header])))
454
+
455
+ def write_to_terraform(result, terraform_dir="./misc/ablation/terraform_config"):
456
+ # define the path to the main.tf file
457
+ terraform_file_path = terraform_dir + "/metric-measurement-main.tf"
458
+ # open the file in write mode ('w') and write the result to it
459
+ # print("CWD", os.getcwd())
460
+ # print("CWD: {}".format(os.getcwd()))
461
+ with open(terraform_file_path, "w+", encoding="utf-8", errors="ignore") as file:
462
+ file.write(result)
463
+ # print(f"Updated main.tf at {terraform_file_path}")
464
+ # print(f"Updated main.tf at {terraform_file_path}")
465
+
466
+ def generate_terraform_plan_json(prompt, terraform_dir="./misc/ablation/terraform_config", plan_file="plan.out", output_json_file="plan.json"):
467
+ cwd = os.getcwd()
468
+ # change to the Terraform directory
469
+ os.chdir(terraform_dir)
470
+ # run init before plan
471
+ init_result = subprocess.run(["terraform", "init"], capture_output=True, text=True)
472
+
473
+ # run 'terraform plan'
474
+ # result = subprocess.run(["terraform", "plan"], capture_output=True, text=True)
475
+
476
+ result_returned = False
477
+ # generate Terraform plan with the -no-color flag
478
+ for i in range(2): # try twice
479
+ try:
480
+ result = subprocess.run(
481
+ ["terraform", "plan", "-out", plan_file, "-no-color"], capture_output=True, text=True, timeout=300 # 5 minutes timeout (assume failed if timeout)
482
+ )
483
+
484
+ with open(
485
+ output_json_file, "w", encoding="utf-8", errors="ignore"
486
+ ) as json_file:
487
+ show_result = subprocess.run(
488
+ ["terraform", "show", "-json", plan_file], check=True, stdout=json_file
489
+ )
490
+
491
+ result_returned = True
492
+ break
493
+ except Exception as e:
494
+ print("Error occurred for prompt \"{}\": {}".format(prompt, e))
495
+
496
+ # Return to parent directory
497
+ os.chdir(cwd)
498
+
499
+ if result_returned == False:
500
+ return "Plan timed-out. No output", "Plan timed-out. No error", False
501
+
502
+
503
+ def main():
504
+ # Find dataset files:
505
+ script_dir = os.path.dirname(os.path.abspath(__file__))
506
+ eval_dataset_dir = os.path.join(script_dir, "../..", "results")
507
+ dataset_dir = os.path.join(script_dir, "../../../data")
508
+ # print()
509
+ excluded_dirs = ["llm-judge-evaluation-metric", "pass"] # skip filenames containing "pass". will merge them into a regular file once done with eval..
510
+ composition_dict = {
511
+ "gpt4": {
512
+ "COT": {
513
+ "complete": [],
514
+ },
515
+ "FSP": {
516
+ "complete": [],
517
+ },
518
+ "multi-turn": {
519
+ "complete": [],
520
+ },
521
+ "RAG": {
522
+ "complete": [],
523
+ },
524
+ "Standard": {
525
+ "complete": [],
526
+ },
527
+ },
528
+ "gpt3.5": {
529
+ "COT": {
530
+ "complete": [],
531
+ },
532
+ "FSP": {
533
+ "complete": [],
534
+ },
535
+ "multi-turn": {
536
+ "complete": [],
537
+ },
538
+ "RAG": {
539
+ "complete": [],
540
+ },
541
+ "Standard": {
542
+ "complete": [],
543
+ },
544
+ },
545
+ "gemini-1.0-pro": {
546
+ "COT": {
547
+ "complete": [],
548
+ },
549
+ "FSP": {
550
+ "complete": [],
551
+ },
552
+ "multi-turn": {
553
+ "complete": [],
554
+ },
555
+ "RAG": {
556
+ "complete": [],
557
+ },
558
+ "Standard": {
559
+ "complete": [],
560
+ },
561
+ },
562
+ "codellama-34b": {
563
+ "COT": {
564
+ "complete": [],
565
+ },
566
+ "FSP": {
567
+ "complete": [],
568
+ },
569
+ "multi-turn": {
570
+ "complete": [],
571
+ },
572
+ "RAG": {
573
+ "complete": [],
574
+ },
575
+ "Standard": {
576
+ "complete": [],
577
+ },
578
+ },
579
+ "codellama-13b": {
580
+ "COT": {
581
+ "complete": [],
582
+ },
583
+ "FSP": {
584
+ "complete": [],
585
+ },
586
+ "multi-turn": {
587
+ "complete": [],
588
+ },
589
+ "RAG": {
590
+ "complete": [],
591
+ },
592
+ "Standard": {
593
+ "complete": [],
594
+ },
595
+ },
596
+ "codellama-7b": {
597
+ "COT": {
598
+ "complete": [],
599
+ },
600
+ "FSP": {
601
+ "complete": [],
602
+ },
603
+ "multi-turn": {
604
+ "complete": [],
605
+ },
606
+ "RAG": {
607
+ "complete": [],
608
+ },
609
+ "Standard": {
610
+ "complete": [],
611
+ },
612
+ },
613
+ "Magicoder_S_CL_7B": {
614
+ "COT": {
615
+ "complete": [],
616
+ },
617
+ "FSP": {
618
+ "complete": [],
619
+ },
620
+ "multi-turn": {
621
+ "complete": [],
622
+ },
623
+ "RAG": {
624
+ "complete": [],
625
+ },
626
+ "Standard": {
627
+ "complete": [],
628
+ },
629
+ },
630
+ "Wizardcoder33b": {
631
+ "COT": {
632
+ "complete": [],
633
+ },
634
+ "FSP": {
635
+ "complete": [],
636
+ },
637
+ "multi-turn": {
638
+ "complete": [],
639
+ },
640
+ "RAG": {
641
+ "complete": [],
642
+ },
643
+ "Standard": {
644
+ "complete": [],
645
+ },
646
+ }
647
+ }
648
+ eval_dataset_files, composition_dict = list_all_subdirectories(composition_dict, eval_dataset_dir, excluded_dirs)
649
+ eval_dataset_files = [f for f in eval_dataset_files if "test" not in f]
650
+ # print(eval_dataset_files)
651
+
652
+ with open(os.path.join(script_dir, 'input_composition_dict.json'), 'w') as fp:
653
+ json.dump(composition_dict, fp)
654
+
655
+ print(composition_dict)
656
+
657
+ output_composition_dict_filepath = os.path.join(script_dir, 'output_composition_dict.json')
658
+
659
+ # Calculate regular metrics
660
+ output_composition_dict = metric_calculation_loop(composition_dict, dataset_dir, output_composition_dict_filepath)
661
+ print("Output composition dict: ", pretty_json(output_composition_dict))
662
+
663
+ with open(output_composition_dict_filepath, 'w') as fp:
664
+ json.dump(output_composition_dict, fp)
665
+
666
+ if __name__ == "__main__":
667
+ main()
human_reference_dataset/iac-eval/evaluation/misc/complete-dataset-measurement/complete-dataset-measurement.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Complexity: LOC, num resources, and number of interconnections.
2
+ # Ambiguity: LLM-judge
3
+ import os
4
+ from pathlib import Path
5
+ import pandas as pd
6
+ import json
7
+ import math
8
+ import statistics
9
+ import time
10
+ import subprocess
11
+ import numpy
12
+ from io import StringIO
13
+ import re
14
+ from collections import defaultdict
15
+ import sys
16
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "evaluation")))
17
+ import models
18
+ import eval
19
+
20
+ def extract_filename(input_string):
21
+ # Define the regular expression pattern to match filenames within quotes that end with .html or .js
22
+ pattern = r'"([^"]+\.(html|js|txt|csv|zip|py|pub|yml|yaml))"'
23
+
24
+ # Search for the pattern in the input string
25
+ match = re.search(pattern, input_string)
26
+
27
+ # Return the matched filename without quotes or None if no match is found
28
+ return match.group(1) if match else None
29
+
30
+ def list_all_subdirectories(data_dir):
31
+ onlyfiles = [os.path.join(dirpath,f) for (dirpath, dirnames, filenames) in os.walk(data_dir) for f in filenames]
32
+ onlyfilescsv = [f for f in onlyfiles if f.endswith(".csv")]
33
+ return onlyfilescsv
34
+
35
+ def create_new_dirs_for_metric(new_base_difficulty_dir, base_dataset_files):
36
+ os.makedirs(new_base_difficulty_dir, exist_ok=True)
37
+ for file in base_dataset_files:
38
+ containing_folder = os.path.basename(os.path.dirname(file)) # e.g., weijun
39
+ filename = os.path.basename(file) # e.g., plain-dataset.csv
40
+ # create the directory if it does not exist
41
+ new_dir_path = os.path.join(new_base_difficulty_dir, containing_folder)
42
+ # print(new_dir_path)
43
+ os.makedirs(new_dir_path, exist_ok=True)
44
+
45
+ def copy_csv_to_metric(base_files, new_base_difficulty_dir):
46
+ """
47
+ Example:
48
+ base_files: ["../data/george/evaluation-dataset-george-gpt3.5.csv"]
49
+ """
50
+ dst_filenames = []
51
+ for file in base_files:
52
+ file_stem = Path(file).stem # https://stackoverflow.com/questions/678236/how-do-i-get-the-filename-without-the-extension-from-a-path-in-python
53
+ containing_folder = os.path.basename(os.path.dirname(file)) # e.g., weijun
54
+ filename = "completed-" + file_stem + ".csv"
55
+ dest_file_path = os.path.join(new_base_difficulty_dir, containing_folder, filename)
56
+ # print(dest_file_path)
57
+ dst_filenames.append(dest_file_path)
58
+ df = pd.read_csv(file, header=None)
59
+ new_header = df.iloc[0]
60
+ df = df[1:]
61
+ df.columns = new_header
62
+ # reset the index of the DataFrame
63
+ df.reset_index(drop=True, inplace=True)
64
+ # add new columns only to df
65
+ # for header in new_difficulty_headers:
66
+ # df[header] = ""
67
+
68
+ df.to_csv(dest_file_path, index=False, encoding="utf-8")
69
+ print(f"Copied and modified CSV to: {dest_file_path}")
70
+ return dst_filenames
71
+
72
+ def difficulty_and_resource_calculation_loop(dst_filenames, script_dir):
73
+ actual_resource_distribution = defaultdict(int) # e.g., "aws_linux_virtual_machine..." : 1
74
+
75
+ complexity_distribution = {
76
+ "level-1": 0,
77
+ "level-2": 0,
78
+ "level-3": 0,
79
+ "level-4": 0,
80
+ "level-5": 0,
81
+ "level-6": 0,
82
+ }
83
+ ambiguity_distribution = {
84
+ "level-1": 0,
85
+ "level-2": 0,
86
+ "level-3": 0,
87
+ "level-4": 0,
88
+ "level-5": 0,
89
+ "level-6": 0,
90
+ }
91
+
92
+ intent_loc_list = []
93
+
94
+ config_metrics = {
95
+ "loc_list": [], # LOC for each row's config
96
+ "interconnections_list": [], # num of interconnections for each row's config
97
+ "resources_list": [] # num of resources for each row's config
98
+ }
99
+
100
+ for file in dst_filenames:
101
+ df = pd.read_csv(file)
102
+ print(f"Begin calc difficulty for dataset {file}")
103
+ # iterate through each row
104
+ for index, row in df.iterrows():
105
+ # iterate every row
106
+ # find specific column
107
+ complexity, resources, intent_loc, config_metric = difficulty_and_resources_calculation(row, df, index)
108
+ if complexity is None:
109
+ continue
110
+
111
+ intent_loc_list.append(intent_loc)
112
+
113
+ config_metrics["loc_list"].append(config_metric[0])
114
+ config_metrics["resources_list"].append(config_metric[1])
115
+ config_metrics["interconnections_list"].append(config_metric[2])
116
+
117
+ for resource in resources:
118
+ actual_resource_distribution[resource] += 1
119
+
120
+ complexity_distribution = update_complexity_distribution(complexity, complexity_distribution)
121
+ # ambiguity_distribution = update_ambiguity_distribution(ambiguity, ambiguity_distribution)
122
+
123
+ print(f"Complexity distribution now: {complexity_distribution}")
124
+ print("Raw resource distribution: ", actual_resource_distribution)
125
+ # print(f"Ambiguity distribution now: {ambiguity_distribution}")
126
+
127
+ df.to_csv(file, index=False, encoding="utf-8")
128
+
129
+ print(f"Finished calc difficulty for dataset {file}")
130
+
131
+ print(f"Final Complexity distribution: {complexity_distribution}")
132
+ with open(os.path.join(script_dir, 'complexity_distribution.json'), 'w') as fp:
133
+ json.dump(complexity_distribution, fp)
134
+ print("Final Raw resource distribution: ", actual_resource_distribution)
135
+ with open(os.path.join(script_dir, 'actual_resource_distribution.json'), 'w') as fp:
136
+ json.dump(actual_resource_distribution, fp)
137
+ get_statistics(intent_loc_list, "Intent LOC")
138
+ get_statistics(config_metrics["loc_list"], "Config LOC")
139
+ get_statistics(config_metrics["resources_list"], "Config resource count")
140
+ get_statistics(config_metrics["interconnections_list"], "Config interconnection count")
141
+ refined_resource_distribution = get_refined_resource_distribution(actual_resource_distribution)
142
+ print("Final refined resource distribution: ", refined_resource_distribution)
143
+ with open(os.path.join(script_dir, 'refined_resource_distribution.json'), 'w') as fp:
144
+ json.dump(refined_resource_distribution, fp)
145
+
146
+ def get_refined_resource_distribution(raw_dist):
147
+ """
148
+ raw_dist format: {
149
+ "aws_lightsail_instance": 1,
150
+ "aws_s3": 1,
151
+ ...
152
+ }
153
+ """
154
+ refined_dist = defaultdict(int)
155
+
156
+ for resource, count in raw_dist.items():
157
+ if "aws_lightsail" in resource:
158
+ refined_dist["aws_lightsail"] += count
159
+ elif "aws_s3" in resource or "aws_glacier" in resource:
160
+ refined_dist["aws_s3"] += count
161
+ elif "aws_sns" in resource:
162
+ refined_dist["aws_sns"] += count
163
+ elif "aws_iam" in resource:
164
+ refined_dist["aws_iam"] += count
165
+ elif "aws_instance" in resource or "aws_ec2" in resource or "aws_ami" in resource or "aws_launch_template" in resource or "aws_placement_group" in resource or "aws_key_pair" in resource:
166
+ refined_dist["aws_ec2"] += count
167
+ elif "aws_lb" in resource or "aws_elb" in resource:
168
+ refined_dist["aws_elb"] += count
169
+ elif "aws_vpc" in resource or "aws_subnet" in resource or "aws_eip" in resource or "aws_egress_only_internet_gateway" in resource or "aws_default_network_acl" in resource or "aws_internet_gateway" in resource or "aws_route_table" in resource or "aws_network_acl" in resource or "aws_vpc_peering_connection" in resource or "aws_nat_gateway" in resource:
170
+ refined_dist["aws_vpc"] += count
171
+ elif "aws_db" in resource or "aws_rds_cluster" in resource:
172
+ refined_dist["aws_rds"] += count
173
+ elif "aws_security_group" in resource:
174
+ refined_dist["aws_security_group"] += count
175
+ elif "aws_cognito" in resource:
176
+ refined_dist["aws_cognito"] += count
177
+ elif "aws_secretsmanager" in resource:
178
+ refined_dist["aws_secretsmanager"] += count
179
+ elif "aws_backup" in resource:
180
+ refined_dist["aws_backup"] += count
181
+ elif "aws_dynamodb" in resource or "aws_dax" in resource:
182
+ refined_dist["aws_dynamodb"] += count
183
+ elif "aws_kms" in resource:
184
+ refined_dist["aws_kms"] += count
185
+ elif "aws_efs" in resource:
186
+ refined_dist["aws_efs"] += count
187
+ elif "aws_msk" in resource:
188
+ refined_dist["aws_msk"] += count
189
+ elif "aws_cloudwatch" in resource:
190
+ refined_dist["aws_cloudwatch"] += count
191
+ elif "aws_kinesis" in resource:
192
+ refined_dist["aws_kinesis"] += count
193
+ elif "aws_autoscaling_group" in resource:
194
+ refined_dist["aws_autoscaling_group"] += count
195
+ elif "aws_elasticache" in resource:
196
+ refined_dist["aws_elasticache"] += count
197
+ elif "aws_redshift" in resource:
198
+ refined_dist["aws_redshift"] += count
199
+ elif "aws_lambda" in resource:
200
+ refined_dist["aws_lambda"] += count
201
+ elif "aws_sagemaker" in resource:
202
+ refined_dist["aws_sagemaker"] += count
203
+ elif "aws_eks" in resource:
204
+ refined_dist["aws_eks"] += count
205
+ elif "aws_codebuild" in resource:
206
+ refined_dist["aws_codebuild"] += count
207
+ elif "aws_api_gateway" in resource:
208
+ refined_dist["aws_api_gateway"] += count
209
+ elif "aws_cloudfront" in resource:
210
+ refined_dist["aws_cloudfront"] += count
211
+ elif "aws_route53" in resource:
212
+ refined_dist["aws_route53"] += count
213
+ elif "aws_lex" in resource:
214
+ refined_dist["aws_lex"] += count
215
+ elif "aws_connect" in resource:
216
+ refined_dist["aws_connect"] += count
217
+ elif "aws_elasticsearch" in resource or "aws_opensearch" in resource:
218
+ refined_dist["aws_elasticsearch"] += count
219
+ elif "aws_kendra" in resource:
220
+ refined_dist["aws_kendra"] += count
221
+ elif "aws_elastic_beanstalk" in resource:
222
+ refined_dist["aws_elastic_beanstalk"] += count
223
+ elif "aws_sqs" in resource:
224
+ refined_dist["aws_sqs"] += count
225
+ elif "aws_neptune" in resource:
226
+ refined_dist["aws_neptune"] += count
227
+ elif "aws_chime" in resource:
228
+ refined_dist["aws_chime"] += count
229
+ else:
230
+ refined_dist[resource] += count
231
+
232
+ return refined_dist
233
+
234
+ def get_statistics(list1, list1_name):
235
+ list1 = sorted(list1)
236
+ x = numpy.quantile(list1, [0,0.25,0.5,0.75,1])
237
+ min1 = x[0]
238
+ max1 = x[4]
239
+ median = x[2]
240
+ q1 = x[1]
241
+ q3 = x[3]
242
+
243
+ print(list1_name + " three quartiles: ", q1, median, q3)
244
+ print(list1_name + " mean: ", statistics.mean(list1))
245
+ print(list1_name + " min: ", min1)
246
+ print(list1_name + " max: ", max1)
247
+
248
+ def update_complexity_distribution(complexity, complexity_distribution):
249
+ if complexity == "1":
250
+ complexity_distribution["level-1"] += 1
251
+ elif complexity == "2":
252
+ complexity_distribution["level-2"] += 1
253
+ elif complexity == "3":
254
+ complexity_distribution["level-3"] += 1
255
+ elif complexity == "4":
256
+ complexity_distribution["level-4"] += 1
257
+ elif complexity == "5":
258
+ complexity_distribution["level-5"] += 1
259
+ elif complexity == "6":
260
+ complexity_distribution["level-6"] += 1
261
+ return complexity_distribution
262
+
263
+ def difficulty_and_resources_calculation(row, df, index):
264
+ prompt = row["Prompt"]
265
+ if isinstance(prompt, float):
266
+ if math.isnan(prompt):
267
+ return None, None, None, None
268
+ reference = row["Reference output"]
269
+ policy = row["Rego intent"]
270
+
271
+ print("Prompt:", prompt)
272
+
273
+ difficulty_level, resource_list, intent_loc, config_metric = calc_difficulty_and_resources(reference, policy, prompt)
274
+ print("Difficulty level: ", difficulty_level)
275
+
276
+ df.at[index, "Difficulty"] = difficulty_level
277
+ df.at[index, "Resource"] = ', '.join(resource_list)
278
+
279
+ return difficulty_level, resource_list, intent_loc, config_metric
280
+
281
+ def calc_difficulty_and_resources(reference, intent, prompt):
282
+ """
283
+ (1) Calculate difficulty based on LOC, num resources, and number of interconnections.
284
+ (2) Obtain all resources, and returns a resource list
285
+ (3) calculate intent loc
286
+ """
287
+ # Calculate LOC:
288
+ LOC = sum(not line.isspace() for line in StringIO(reference))
289
+ print("LOC", LOC)
290
+
291
+ # Calculate intent LOC:
292
+ intent_loc = sum(not line.isspace() for line in StringIO(intent))
293
+ print("Intent LOC: ", intent_loc)
294
+
295
+ # Calculate number of resources:
296
+ # Count the number of occurences of the word "resource" in the reference string
297
+ num_resources = reference.count("resource")
298
+ print("num_resources", num_resources)
299
+
300
+ terraform_dir = "./misc/complete-dataset-measurement/terraform_config"
301
+
302
+ eval.delete_all_files_in_directory(terraform_dir)
303
+
304
+ # Calculate number of interconnections:
305
+ write_to_terraform(reference)
306
+ # run terraform plan and capture the output and errors
307
+ plan_file = "plan.out"
308
+ output_json_file = "plan.json"
309
+ output_json_filepath = os.path.join(terraform_dir, output_json_file)
310
+ generate_terraform_plan_json(prompt, terraform_dir, plan_file, output_json_file)
311
+
312
+ # Check that Rego intents are correct/parsable:
313
+ rego_dir = "./misc/complete-dataset-measurement/rego_config"
314
+ rego_policy_filepath = rego_dir + "/policy.rego"
315
+ eval.write_to_rego(intent, rego_policy_filepath)
316
+ opa_result, opa_error = eval.OPA_Rego_evaluation(output_json_filepath, rego_policy_filepath)
317
+ if "OPA exception occurred" in opa_error:
318
+ sys.exit(opa_error)
319
+
320
+ # read the json file
321
+ # print("about to read json..")
322
+ resource_list = []
323
+ with open(output_json_filepath, "r") as json_file:
324
+ data = json.load(json_file)
325
+ # extract the number of interconnections from the json file
326
+ config_graph = data["configuration"]["root_module"]["resources"]
327
+ for i in config_graph:
328
+ resource_list.append(i["type"])
329
+ references_list = list(findkeys(config_graph, "references")) # just a list with the word "references" repeated
330
+ # print(references_list)
331
+ num_interconnections = len(references_list)
332
+ print("num_interconnections", num_interconnections)
333
+ print("Resources found: ", resource_list)
334
+ # Determine difficulty:
335
+ return get_difficulty_level(LOC, num_resources, num_interconnections), resource_list, intent_loc, [LOC, num_resources, num_interconnections]
336
+
337
+ def get_difficulty_level(LOC, num_resources, num_interconnections):
338
+ if LOC < 10 and num_resources < 2 and num_interconnections < 2:
339
+ return "1"
340
+ if LOC < 20 and num_resources < 4 and num_interconnections < 4:
341
+ return "2"
342
+ if LOC < 40 and num_resources < 6 and num_interconnections < 6:
343
+ return "3"
344
+ if LOC < 60 and num_resources < 8 and num_interconnections < 8:
345
+ return "4"
346
+ if LOC < 80 and num_resources < 10 and num_interconnections < 10:
347
+ return "5"
348
+ if LOC >= 80 or num_resources >= 10 or num_interconnections >= 10:
349
+ return "6"
350
+
351
+ def findkeys(node, kv):
352
+ # Modified from: https://stackoverflow.com/a/19871956/13336187
353
+ if isinstance(node, list):
354
+ for i in node:
355
+ for x in findkeys(i, kv):
356
+ yield x
357
+ elif isinstance(node, dict):
358
+ if kv in node:
359
+ yield kv
360
+ for j in node.values():
361
+ for x in findkeys(j, kv):
362
+ yield x
363
+
364
+ # print(list(findkeys(d, 'id')))
365
+
366
+ def write_to_terraform(result, terraform_dir="./misc/complete-dataset-measurement/terraform_config"):
367
+ # define the path to the main.tf file
368
+ terraform_file_path = terraform_dir + "/complete-measurement-main.tf"
369
+ os.makedirs(terraform_dir, exist_ok=True)
370
+ # open the file in write mode ('w') and write the result to it
371
+ # print("CWD", os.getcwd())
372
+ print("CWD: {}".format(os.getcwd()))
373
+ with open(terraform_file_path, "w+", encoding="utf-8", errors="ignore") as file:
374
+ file.write(result)
375
+ # print(f"Updated main.tf at {terraform_file_path}")
376
+ print(f"Updated main.tf at {terraform_file_path}")
377
+
378
+ def plan_error_handling(result):
379
+ error_handled = False
380
+
381
+ if "Inconsistent dependency lock file" in result.stderr:
382
+ init_result = subprocess.run(["terraform", "init"], capture_output=True, text=True)
383
+ time.sleep(5)
384
+ error_handled = True
385
+ # assumes only one missing file, at least per iteration..
386
+ elif "archive missing file: " in result.stderr: # error seen in data "archive_file"
387
+ print("Missing archive file... trying again. Result stderr is: ")
388
+ print(result.stderr)
389
+ for item in result.stderr.split("\n"): # Get line containing string: https://stackoverflow.com/questions/2557808/search-and-get-a-line-in-python
390
+ missing_filename = extract_filename(item)
391
+ if missing_filename is not None:
392
+ with open(missing_filename, "w") as file:
393
+ print("Creating missing archive file: ", missing_filename)
394
+ file.write("random")
395
+ error_handled = True
396
+ elif "no file exists at" in result.stderr: # error seen in file("sagemaker-human-task-ui-template.html") attribute value
397
+ print("Missing file... trying again. Result stderr is: ")
398
+ print(result.stderr)
399
+ for item in result.stderr.split("\n"): # Get line containing string: https://stackoverflow.com/questions/2557808/search-and-get-a-line-in-python
400
+ missing_filename = extract_filename(item)
401
+ if missing_filename is not None:
402
+ with open(missing_filename, "w") as file:
403
+ print("Creating missing file: ", missing_filename)
404
+ file.write("random")
405
+ error_handled = True
406
+ return error_handled
407
+
408
+ def generate_terraform_plan_json(prompt, terraform_dir="./misc/complete-dataset-measurement/terraform_config", plan_file="plan.out", output_json_file="plan.json"):
409
+ cwd = os.getcwd()
410
+ # change to the Terraform directory
411
+ os.chdir(terraform_dir)
412
+
413
+ for i in range(3): # try twice
414
+ try:
415
+ # run init before plan
416
+ result = subprocess.run(["terraform", "init"], capture_output=True, text=True)
417
+
418
+ error_handled = plan_error_handling(result)
419
+
420
+ if error_handled:
421
+ continue
422
+
423
+ # generate Terraform plan with the -no-color flag
424
+ result = subprocess.run(
425
+ ["terraform", "plan", "-out", plan_file, "-no-color"], capture_output=True, text=True, timeout=60
426
+ )
427
+
428
+ error_handled = plan_error_handling(result)
429
+
430
+ if error_handled:
431
+ continue
432
+
433
+ with open(
434
+ output_json_file, "w", encoding="utf-8", errors="ignore"
435
+ ) as json_file:
436
+ result = subprocess.run(
437
+ ["terraform", "show", "-json", plan_file], check=True, stdout=json_file
438
+ )
439
+
440
+ break
441
+ except Exception as e:
442
+ print("Error occurred for prompt \"{}\": {}".format(prompt, e))
443
+
444
+ # Return to parent directory
445
+ os.chdir(cwd)
446
+
447
+ def main():
448
+ # Find dataset files:
449
+ script_dir = os.path.dirname(os.path.abspath(__file__))
450
+ dataset_dir = os.path.join(script_dir, "../../..", "data")
451
+ # dataset_dir = os.path.join(script_dir, "../../..", "delete-later-fake-complete")
452
+ # print()
453
+ dataset_files = list_all_subdirectories(dataset_dir)
454
+ dataset_files = [f for f in dataset_files if "test" not in f]
455
+ print(dataset_files)
456
+
457
+ difficulty_included_dataset_dir = script_dir + "/complete-dataset"
458
+ create_new_dirs_for_metric(difficulty_included_dataset_dir, dataset_files)
459
+ dst_filenames = copy_csv_to_metric(dataset_files, difficulty_included_dataset_dir)
460
+ # print(dst_filenames)
461
+ difficulty_and_resource_calculation_loop(dst_filenames, script_dir)
462
+
463
+ # Display number of rows for each complexity level:
464
+
465
+ if __name__ == "__main__":
466
+ main()
467
+ # reference = """
468
+ # terraform {
469
+ # required_providers {
470
+ # aws = {
471
+ # source = "hashicorp/aws"
472
+ # version = "~> 4.16"
473
+ # }
474
+ # }
475
+
476
+ # required_version = ">= 1.2.0"
477
+ # }
478
+ # # Define the provider block for AWS
479
+ # provider "aws" {
480
+ # region = "us-east-2" # Set your desired AWS region
481
+ # }
482
+
483
+ # variable "vpc_id" {
484
+ # type = string
485
+ # description = "The VPC to deploy the components within"
486
+ # default = "vpc-12345678"
487
+ # }
488
+
489
+ # variable "pg_port" {
490
+ # type = number
491
+ # description = "Postgres connection port"
492
+ # default = 5432
493
+ # }
494
+
495
+ # variable "pg_superuser_username" {
496
+ # type = string
497
+ # description = "Username for the 'superuser' user in the Postgres instance"
498
+ # default = "superuser"
499
+ # }
500
+
501
+ # variable "pg_superuser_password" {
502
+ # type = string
503
+ # sensitive = true
504
+ # description = "Password for the 'superuser' user in the Postgres instance"
505
+ # default = "random-password"
506
+ # }
507
+
508
+ # resource "aws_db_subnet_group" "postgres" {
509
+ # name = "pgsubnetgrp"
510
+ # subnet_ids = [aws_subnet.main1.id, aws_subnet.main2.id]
511
+ # }
512
+
513
+ # resource "aws_subnet" "main1" {
514
+ # vpc_id = var.vpc_id
515
+ # cidr_block = "10.0.1.0/24"
516
+
517
+ # tags = {
518
+ # Name = "Main"
519
+ # }
520
+ # }
521
+
522
+ # resource "aws_subnet" "main2" {
523
+ # vpc_id = var.vpc_id
524
+ # cidr_block = "10.0.1.0/24"
525
+
526
+ # tags = {
527
+ # Name = "Main"
528
+ # }
529
+ # }
530
+
531
+ # resource "aws_db_parameter_group" "postgres" {
532
+ # name = "pgparamgrp15"
533
+ # family = "postgres15"
534
+
535
+ # parameter {
536
+ # name = "password_encryption"
537
+ # value = "scram-sha-256"
538
+ # }
539
+
540
+ # parameter {
541
+ # name = "rds.force_ssl"
542
+ # value = "0"
543
+ # }
544
+
545
+ # lifecycle {
546
+ # create_before_destroy = true
547
+ # }
548
+ # }
549
+
550
+ # resource "aws_security_group" "pg" {
551
+ # name = "pg"
552
+ # vpc_id = var.vpc_id
553
+
554
+ # ingress {
555
+ # description = "Postgres from internet"
556
+ # from_port = 5432
557
+ # to_port = 5432
558
+ # cidr_blocks = ["0.0.0.0/0"]
559
+ # protocol = "TCP"
560
+ # self = false
561
+ # }
562
+ # egress {
563
+ # description = "Postgres to internet"
564
+ # from_port = 5432
565
+ # to_port = 5432
566
+ # cidr_blocks = ["0.0.0.0/0"]
567
+ # protocol = "TCP"
568
+ # self = false
569
+ # }
570
+ # }
571
+
572
+ # resource "aws_kms_key" "rds_key" {
573
+ # description = "kmsrds"
574
+ # deletion_window_in_days = 14
575
+ # tags = { Name = "kmsrds" }
576
+ # }
577
+
578
+ # resource "aws_db_instance" "postgres" {
579
+ # identifier = "pg"
580
+ # final_snapshot_identifier = "pgsnapshot"
581
+ # allocated_storage = 20
582
+ # apply_immediately = true
583
+ # backup_retention_period = 7
584
+ # db_subnet_group_name = aws_db_subnet_group.postgres.name
585
+ # parameter_group_name = aws_db_parameter_group.postgres.name
586
+ # enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]
587
+ # engine = "postgres"
588
+ # engine_version = "15"
589
+ # allow_major_version_upgrade = true
590
+ # instance_class = "db.t3.micro"
591
+ # db_name = "postgres" # Initial database name
592
+ # username = var.pg_superuser_username
593
+ # port = var.pg_port
594
+ # password = var.pg_superuser_password
595
+ # vpc_security_group_ids = [aws_security_group.pg.id]
596
+ # # Other security settings
597
+ # publicly_accessible = false
598
+ # multi_az = true
599
+ # storage_encrypted = true
600
+ # kms_key_id = aws_kms_key.rds_key.arn
601
+ # # Default daily backup window
602
+ # # https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html#USER_WorkingWithAutomatedBackups.BackupWindow
603
+ # }
604
+ # """
605
+ # prompt = "provisions a secure PostgreSQL database instance within a specified AWS VPC, leveraging AWS services like RDS, subnets, and KMS for encryption. It sets up two subnets within the VPC for the database, a custom parameter group for PostgreSQL settings, and a security group to manage access. The database instance is configured with specifics storage size is 20GB, engine version is 15, multi-AZ deployment for high availability, and encryption using a KMS key."
606
+ # print(calc_complexity(reference, prompt))
human_reference_dataset/iac-eval/evaluation/misc/sagemaker_setup/sagemaker-magicoder-s-cl-7b-deploy.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Partial reference (incredibly bad documentation and outdated to top it off): https://github.com/huggingface/notebooks/blob/main/sagemaker/11_deploy_model_from_hf_hub/deploy_transformer_model_from_hf_hub.ipynb
2
+ import json
3
+ import sagemaker
4
+ import boto3
5
+ import time
6
+ from sagemaker.huggingface import HuggingFaceModel, get_huggingface_llm_image_uri
7
+
8
+ try:
9
+ role_name = input("Enter the AWS role name, of the AWS account which you will use to create a Sagemaker model/endpoint: ")
10
+ sagemaker_execution_role = input("Enter the AWS SageMaker execution role, which will be used to create a Sagemaker model/endpoint: ") # e.g., AmazonSageMaker-ExecutionRole-20240504T121584
11
+ my_session = boto3.session.Session(profile_name=role_name)
12
+ sagemaker_session = sagemaker.Session(my_session)
13
+ # print(sagemaker_session.boto_session.region_name)
14
+ # role = sagemaker.get_execution_role(sagemaker_session=sagemaker_session)
15
+ iam = my_session.client('iam')
16
+ role = iam.get_role(RoleName=sagemaker_execution_role)['Role']['Arn']
17
+ # print(sagemaker_session.get_caller_identity_arn())
18
+ print(role)
19
+ # role = sagemaker.get_execution_role()
20
+
21
+ print("Finished sagemaker session setup.")
22
+ except ValueError:
23
+ my_session = boto3.session.Session(profile_name=role_name)
24
+ # sagemaker.Session(my_session)
25
+ # sagemaker_session = 1
26
+ iam = my_session.client('iam')
27
+ role = iam.get_role(RoleName=sagemaker_execution_role)['Role']['Arn']
28
+ print(role)
29
+
30
+ # Hub Model configuration. https://huggingface.co/models
31
+ hub = {
32
+ 'HF_MODEL_ID':'ise-uiuc/Magicoder-S-CL-7B', # https://huggingface.co/ise-uiuc/Magicoder-S-CL-7B
33
+ # 'HF_MODEL_ID':'ise-uiuc/Magicoder-S-DS-6.7B', # https://huggingface.co/ise-uiuc/Magicoder-S-DS-6.7B?sagemaker_deploy=true
34
+ # 'HF_MODEL_ID':'Salesforce/codegen-16B-multi', # https://huggingface.co/Salesforce/codegen-16B-multi?sagemaker_deploy=true
35
+ 'SM_NUM_GPUS': json.dumps(1), # add back later. for bert testing. # Only 1 GPU is avail for g5.2xlarge instance https://aws.amazon.com/ec2/instance-types/g5/
36
+ 'HF_TASK':'text-generation',
37
+ # 'HF_TASK':'question-answering' # NLP task you want to use for predictions
38
+ # "region": "us-east-1",
39
+ # https://datamagiclab.com/input-validation-error-inputs-tokens-max_new_tokens-must-be-2048/ # https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1/discussions/199
40
+ "MAX_INPUT_LENGTH": '4000', # put here any value upto 32768 as per your requirement.
41
+ "MAX_TOTAL_TOKENS": '5000',
42
+ "MAX_BATCH_PREFILL_TOKENS": '5000',
43
+ "MAX_BATCH_TOTAL_TOKENS": '5000',
44
+ }
45
+
46
+ # create Hugging Face Model Class
47
+ huggingface_model = HuggingFaceModel(
48
+ image_uri=get_huggingface_llm_image_uri("huggingface",version="1.4.2",
49
+ session=sagemaker_session
50
+ ),
51
+ env=hub,
52
+ role=role,
53
+ sagemaker_session=sagemaker_session,
54
+ # Remove later, for bert testing:
55
+ # transformers_version='4.37.0',
56
+ # pytorch_version='2.1.0',
57
+ # py_version='py310',
58
+ )
59
+
60
+ # deploy model to SageMaker Inference
61
+ predictor = huggingface_model.deploy(
62
+ initial_instance_count=1,
63
+ instance_type="ml.g5.2xlarge",
64
+ # instance_type="ml.g5.4xlarge",
65
+ # instance_type="ml.m5.xlarge",
66
+ container_startup_health_check_timeout=300, # add back later. for bert testing.
67
+ )
68
+
69
+ MAGICODER_PROMPT = """You are an exceptionally intelligent coding assistant that consistently delivers accurate and reliable responses to user instructions.
70
+
71
+ @@ Instruction
72
+ {}
73
+
74
+ @@ Response
75
+ """.format("You are TerraformAI, an AI agent that builds and deploys Cloud Infrastructure written in Terraform HCL. Generate a description of the Terraform program you will define, followed by a single Terraform HCL program in response to each of my Instructions. Make sure the configuration is deployable. Create IAM roles as needed. If variables are used, make sure default values are supplied. \n Here is the actual prompt: Create an AWS VPC resource with an Internet Gateway attached to it")
76
+
77
+ # send request
78
+ print(predictor.predict({
79
+ "inputs": MAGICODER_PROMPT,
80
+ }))
81
+
82
+
83
+ time.sleep(60)
84
+
85
+ print(predictor.predict({
86
+ "inputs": "My name is Julien and I like to",
87
+ }))
88
+ # # Cleanup:
89
+ # predictor.delete_model()
90
+ # predictor.delete_endpoint()
human_reference_dataset/iac-eval/evaluation/models.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import replicate
2
+ import google.generativeai as genai
3
+ import os
4
+ import requests
5
+ import boto3
6
+ import sagemaker
7
+ import json
8
+ import subprocess
9
+ import time
10
+
11
+ # GPT evaluation generation
12
+ # set your API key here, need to be hided
13
+ def GPT3_5(preprompt, prompt, client):
14
+ # message = query_message(prompt) if KNOWLEDGE_EMBEDDING_FLAG else prompt
15
+ messages = [
16
+ {"role": "system", "content": preprompt},
17
+ {"role": "user", "content": prompt},
18
+ ]
19
+
20
+ while True:
21
+ try:
22
+ response = client.chat.completions.create(
23
+ model="gpt-3.5-turbo",
24
+ messages=messages,
25
+ )
26
+ # print(response.choices[0].message.content)
27
+ # print("GPT3.5 eval done")
28
+ return response.choices[0].message.content
29
+ except Exception as e:
30
+ s = str(e)
31
+ if "Rate limit is exceeded" in s:
32
+ time.sleep(30)
33
+ continue
34
+ else:
35
+ return ""
36
+
37
+ def GPT4(preprompt, prompt, client):
38
+ # print("current GPT4 working directory is",os.getcwd())
39
+ # message = query_message(prompt) if KNOWLEDGE_EMBEDDING_FLAG else prompt
40
+ messages = [
41
+ {"role": "system", "content": preprompt},
42
+ {"role": "user", "content": prompt},
43
+ ]
44
+ while True:
45
+ try:
46
+ response = client.chat.completions.create(
47
+ model="gpt-4-turbo",
48
+ messages=messages,
49
+ )
50
+
51
+ # print(response.choices[0].message.content)
52
+ # print("GPT4 eval done")
53
+ return response.choices[0].message.content
54
+ except Exception as e:
55
+ s = str(e)
56
+ if "Rate limit is exceeded" in s:
57
+ time.sleep(30)
58
+ continue
59
+ else:
60
+ return ""
61
+
62
+ def Codellama7b(preprompt, prompt):
63
+ for i in range(2):
64
+ try:
65
+ output = replicate.run(
66
+ "meta/codellama-7b-instruct:aac3ab196f8a75729aab9368cd45ea6ad3fc793b6cda93b1ded17299df369332",
67
+ input={
68
+ "top_k": 250,
69
+ "top_p": 0.95,
70
+ "prompt": prompt,
71
+ "max_tokens": 500,
72
+ "temperature": 0.95,
73
+ "system_prompt": preprompt,
74
+ "repeat_penalty": 1.1,
75
+ "presence_penalty": 0,
76
+ "frequency_penalty": 0,
77
+ },
78
+ )
79
+ output_string = ""
80
+ for item in output:
81
+ output_string += item
82
+ print(output_string)
83
+ return output_string
84
+ except Exception as e:
85
+ s = str(e)
86
+ print(s)
87
+ if "status: 502" in s or "Prediction interrupted" in s:
88
+ time.sleep(10)
89
+ return ""
90
+
91
+
92
+ def Codellama13b(preprompt, prompt):
93
+ for i in range(2):
94
+ try:
95
+ output = replicate.run(
96
+ "meta/codellama-13b-instruct:a5e2d67630195a09b96932f5fa541fe64069c97d40cd0b69cdd91919987d0e7f",
97
+ input={
98
+ "top_k": 250,
99
+ "top_p": 0.95,
100
+ "prompt": prompt,
101
+ "max_tokens": 500,
102
+ "temperature": 0.95,
103
+ "system_prompt": preprompt,
104
+ "repeat_penalty": 1.1,
105
+ "presence_penalty": 0,
106
+ "frequency_penalty": 0,
107
+ },
108
+ )
109
+ output_string = ""
110
+ for item in output:
111
+ output_string += item
112
+ print(output_string)
113
+ return output_string
114
+ except Exception as e:
115
+ s = str(e)
116
+ print(s)
117
+ if "status: 502" in s or "Prediction interrupted" in s:
118
+ time.sleep(10)
119
+ return ""
120
+
121
+
122
+ def Codellama34b(preprompt, prompt):
123
+ for i in range(2):
124
+ try:
125
+ output = replicate.run(
126
+ "meta/codellama-34b-instruct:eeb928567781f4e90d2aba57a51baef235de53f907c214a4ab42adabf5bb9736",
127
+ input={
128
+ "top_k": 250,
129
+ "top_p": 0.95,
130
+ "prompt": prompt,
131
+ "max_tokens": 500,
132
+ "temperature": 0.95,
133
+ "system_prompt": preprompt,
134
+ "repeat_penalty": 1.1,
135
+ "presence_penalty": 0,
136
+ "frequency_penalty": 0,
137
+ },
138
+ )
139
+ output_string = ""
140
+ for item in output:
141
+ output_string += item
142
+ print(output_string)
143
+ return output_string
144
+ except Exception as e:
145
+ s = str(e)
146
+ print(s)
147
+ if "status: 502" in s or "Prediction interrupted" in s:
148
+ time.sleep(10)
149
+ return ""
150
+
151
+ # Codegen model variants: https://replicate.com/andreasjansson/codegen
152
+ def Codegen16b(preprompt, prompt):
153
+ API_URL = "https://api-inference.huggingface.co/models/gpt2"
154
+ HF_API_TOKEN = os.environ['HF_API_TOKEN ']
155
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
156
+ response = requests.post(API_URL, headers=headers, json=prompt)
157
+
158
+ return response.json()
159
+
160
+ # https://replicate.com/rhamnett/wizardcoder-34b-v1.0
161
+ def Wizardcoder34b(preprompt, prompt):
162
+ for i in range(2):
163
+ try:
164
+ output = replicate.run(
165
+ "rhamnett/wizardcoder-34b-v1.0:bae902bd8a4032fcf2295523b38da90aae7cc8ca2260e7ca9b8434a981d32278",
166
+ input={
167
+ "top_k": 250,
168
+ "top_p": 0.95,
169
+ "prompt": prompt,
170
+ "max_tokens": 500,
171
+ "temperature": 0.95,
172
+ "system_prompt": preprompt,
173
+ "repeat_penalty": 1.1,
174
+ "presence_penalty": 0,
175
+ "frequency_penalty": 0,
176
+ },
177
+ )
178
+ output_string = ""
179
+ for item in output:
180
+ output_string += item
181
+ print(output_string)
182
+ return output_string
183
+ except Exception as e:
184
+ s = str(e)
185
+ print(s)
186
+ if "status: 502" in s or "Prediction interrupted" in s:
187
+ time.sleep(10)
188
+ return ""
189
+
190
+
191
+ # WizardCoder-Python-34B-V1.0 https://replicate.com/lucataco/wizardcoder-python-34b-v1.0
192
+
193
+ # WizardCoder-33B-V1.1 : https://replicate.com/lucataco/wizardcoder-33b-v1.1-gguf
194
+ def Wizardcoder33b(preprompt, prompt):
195
+ for i in range(2):
196
+ try:
197
+ output = replicate.run(
198
+ "lucataco/wizardcoder-33b-v1.1-gguf:bbf93cee2c2b446f0ff426ae81a9b61c5ebd8972a21f734fe035513b6fafe615",
199
+ input={
200
+ "top_k": 250,
201
+ "top_p": 0.95,
202
+ "prompt": prompt,
203
+ "max_tokens": 500,
204
+ "temperature": 0.95,
205
+ "system_prompt": preprompt,
206
+ "repeat_penalty": 1.1,
207
+ "presence_penalty": 0,
208
+ "frequency_penalty": 0,
209
+ },
210
+ )
211
+ output_string = ""
212
+ for item in output:
213
+ output_string += item
214
+ print(output_string)
215
+ return output_string
216
+ except Exception as e:
217
+ s = str(e)
218
+ print(s)
219
+ if "status: 502" in s or "Prediction interrupted" in s:
220
+ time.sleep(10)
221
+ return ""
222
+
223
+ def Magicoder_S_CL_7B(preprompt, prompt):
224
+ while True:
225
+ try:
226
+ my_session = boto3.session.Session(profile_name=os.environ["AWS_ROLE_NAME"])
227
+ session = sagemaker.Session(my_session)
228
+ # endpoint_name = "huggingface-pytorch-tgi-inference-2024-05-06-03-21-48-837" # ise-uiuc/Magicoder-S-CL-7B endpoint
229
+ endpoint_name = os.environ["MAGICODER_SAGEMAKER_ENDPOINT"] # ise-uiuc/Magicoder-S-CL-7B endpoint with 5000 MAX_TOTAL_TOKENS
230
+ predictor = sagemaker.predictor.RealTimePredictor(endpoint_name=endpoint_name, sagemaker_session=session)
231
+ MAGICODER_PROMPT = """
232
+ You are an exceptionally intelligent coding assistant that consistently delivers accurate and reliable responses to user instructions.
233
+
234
+ @@ Instruction
235
+ {}
236
+
237
+ @@ Response
238
+ """.format(preprompt + "\n" + prompt)
239
+ input_data = {
240
+ "inputs": MAGICODER_PROMPT,
241
+ 'parameters': {"stop": ["<|endoftext|>", "</s>"], "max_new_tokens": 1000} # https://stackoverflow.com/a/76763217/13336187 # NOTE: 1800 max_new_tokens I initially used
242
+ }
243
+ payload = json.dumps(input_data).encode("utf-8")
244
+ result = predictor.predict(payload, initial_args={'ContentType': 'application/json'}) # https://stackoverflow.com/a/65448063/13336187
245
+ json_data = json.loads(result.decode('utf-8'))
246
+ generated_text = json_data[0]['generated_text'].split("@@ Response")[1]
247
+ return generated_text
248
+ except Exception as e:
249
+ s = str(e)
250
+ if "Your invocation timed out" in s:
251
+ print("Error encoutered. Considered model unable to output correct answer: ", s)
252
+ return ""
253
+ else:
254
+ print("Error: ", s)
255
+ raise e
256
+
257
+ # WizardCoder-15B-V1.0 https://replicate.com/lucataco/wizardcoder-15b-v1.0
258
+ # def Wizardcoder33b(preprompt, prompt):
259
+ # output = replicate.run(
260
+ # "lucataco/wizardcoder-33b-v1.1-gguf:bbf93cee2c2b446f0ff426ae81a9b61c5ebd8972a21f734fe035513b6fafe615",
261
+ # input={
262
+ # "top_k": 250,
263
+ # "top_p": 0.95,
264
+ # "prompt": prompt,
265
+ # "max_tokens": 500,
266
+ # "temperature": 0.95,
267
+ # "system_prompt": preprompt,
268
+ # "repeat_penalty": 1.1,
269
+ # "presence_penalty": 0,
270
+ # "frequency_penalty": 0,
271
+ # },
272
+ # )
273
+ # output_string = ""
274
+ # for item in output:
275
+ # output_string += item
276
+ # print(output_string)
277
+ # return output_string
278
+
279
+
280
+ # Gemini: https://ai.google.dev/gemini-api/docs/quickstart https://github.com/alibaba/CloudEval-YAML/blob/main/models/palm.py
281
+ def gemini(preprompt, prompt):
282
+ genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
283
+ # for m in genai.list_models():
284
+ # if 'generateContent' in m.supported_generation_methods:
285
+ # print(m.name)
286
+
287
+ safety_settings = [
288
+ {
289
+ "category": "HARM_CATEGORY_DANGEROUS",
290
+ "threshold": "BLOCK_NONE",
291
+ },
292
+ {
293
+ "category": "HARM_CATEGORY_HARASSMENT",
294
+ "threshold": "BLOCK_NONE",
295
+ },
296
+ {
297
+ "category": "HARM_CATEGORY_HATE_SPEECH",
298
+ "threshold": "BLOCK_NONE",
299
+ },
300
+ {
301
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
302
+ "threshold": "BLOCK_NONE",
303
+ },
304
+ {
305
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
306
+ "threshold": "BLOCK_NONE",
307
+ },
308
+ ]
309
+
310
+ model = genai.GenerativeModel('gemini-pro')
311
+ # print(preprompt + "\n" + prompt)
312
+ while True:
313
+ try:
314
+ response = model.generate_content(preprompt + "\n" + prompt, safety_settings=safety_settings)
315
+ break
316
+ except Exception as e:
317
+ s = str(e)
318
+ if "Resource has been exhausted" in s:
319
+ print(s)
320
+ print("^ Resource has been exhausted. Please wait for 100 seconds.")
321
+ time.sleep(100)
322
+ # print(len(response.candidates))
323
+ # for candidate in response.candidates:
324
+ # print(len(candidate.content.parts))
325
+ # print ([part.text for part in candidate.content.parts])
326
+
327
+ # return response.text
328
+ try:
329
+ res = response.candidates[0].content.parts[0].text # https://github.com/google-gemini/generative-ai-python/issues/170
330
+ return res
331
+ except:
332
+ return ""
333
+
334
+ # gemini("You are TerraformAI, an AI agent that builds and deploys Cloud Infrastructure written in Terraform HCL. Generate a description of the Terraform program you will define, followed by a single Terraform HCL program in response to each of my Instructions. Make sure the configuration is deployable. Create IAM roles as needed.", "create a AWS codebuild project resource with example iam role, example GITHUB source, and a logs config")
335
+
336
+ # print(Magicoder_S_CL_7B("You are TerraformAI, an AI agent that builds and deploys Cloud Infrastructure written in Terraform HCL. Generate a description of the Terraform program you will define, followed by a single Terraform HCL program in response to each of my Instructions. Make sure the configuration is deployable. Create IAM roles as needed. If variables are used, make sure default values are supplied.", "Here is the actual prompt: Create an AWS VPC resource with an Internet Gateway attached to it"))
337
+
338
+ # print(Wizardcoder34b("You are TerraformAI, an AI agent that builds and deploys Cloud Infrastructure written in Terraform HCL. Generate a description of the Terraform program you will define, followed by a single Terraform HCL program in response to each of my Instructions. Make sure the configuration is deployable. Create IAM roles as needed. If variables are used, make sure default values are supplied.", "Here is the actual prompt: Create an AWS VPC resource with an Internet Gateway attached to it"))
human_reference_dataset/iac-eval/evaluation/prompt-templates/CoT.txt ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Here are a few examples:
2
+
3
+ Example prompt 1: Create an AWS RDS instance (with an instance class of db.t2.micro, and don't create a final snapshot before eventual deletion) with randomly generated id and password
4
+ Example output 1: Let's think step by step. First, let's reason about the resources needed: this would be an AWS RDS instance (aws_db_instance), and resources to generate a random id and password. Second, we fill in the attributes of each resource, starting with those explicitly and implicitly mentioned in the prompt, and followed by others: for example, for the aws_db_instance, we need to set the "instance_class" attribute to "db.t2.micro", and the "skip_final_snapshot" attribute to true. Finally, we connect the resources together, as needed: here "identifier" should be connected to the "random_id" resource, and "password" should be connected to the "random_password" resource
5
+ ```hcl
6
+ resource "random_id" "suffix" {
7
+ byte_length = 4
8
+ }
9
+
10
+ resource "random_password" "db" {
11
+ length = 16
12
+ special = false
13
+ }
14
+
15
+ resource "aws_db_instance" "test" {
16
+ identifier = "metricbeat-test-${random_id.suffix.hex}"
17
+ allocated_storage = 20 // Gigabytes
18
+ engine = "mysql"
19
+ instance_class = "db.t2.micro"
20
+ db_name = "metricbeattest"
21
+ username = "foo"
22
+ password = random_password.db.result
23
+ skip_final_snapshot = true // Required for cleanup
24
+ }
25
+ ```
26
+
27
+ Example prompt 2: Create an 20GB MySQL instance on aws with randomly generated id and password
28
+ Example output 2: Let's think step by step. First, let's reason about the resources needed: this would be an AWS RDS instance (aws_db_instance), and resources to generate a random id and password. Second, we fill in the attributes of each resource, starting with those explicitly and implicitly mentioned in the prompt, and followed by others: for example, for the aws_db_instance, we need to set the "engine" attribute to "mysql". Finally, we connect the resources together, as needed: here "identifier" should be connected to the "random_id" resource, and "password" should be connected to the "random_password" resource
29
+ ```hcl
30
+ resource "random_id" "suffix" {
31
+ byte_length = 4
32
+ }
33
+
34
+ resource "random_password" "db" {
35
+ length = 16
36
+ special = false
37
+ }
38
+
39
+ resource "aws_db_instance" "test" {
40
+ identifier = "metricbeat-test-${random_id.suffix.hex}"
41
+ allocated_storage = 20 // Gigabytes
42
+ engine = "mysql"
43
+ instance_class = "db.t2.micro"
44
+ db_name = "metricbeattest"
45
+ username = "foo"
46
+ password = random_password.db.result
47
+ skip_final_snapshot = true // Required for cleanup
48
+ }
49
+ ```
50
+
51
+ Example prompt 3: create a AWS EFS, and create a replica of an this created EFS file system using regional storage in us-west-2
52
+ Example output 3: Let's think step by step. First, let's reason about the resources needed: this would be an AWS EFS replication resource (aws_efs_replication_configuration), and the AWS EFS resource itself. Second, we fill in the attributes of each resource, starting with those explicitly and implicitly mentioned in the prompt, and followed by others: for example, for the aws_efs_replication_configuration, we need to set the "availability_zone_name" attribute to an availability zone that will be within the region specificed in the prompt, such as "us-west-2b". Finally, we connect the resources together, as needed: here "source_file_system_id" should be connected to the "aws_efs_file_system" resource
53
+ ```hcl
54
+ resource "aws_efs_file_system" "example" {}
55
+
56
+ resource "aws_efs_replication_configuration" "example" {
57
+ source_file_system_id = aws_efs_file_system.example.id
58
+
59
+ destination {
60
+ availability_zone_name = "us-west-2b"
61
+ kms_key_id = "1234abcd-12ab-34cd-56ef-1234567890ab"
62
+ }
63
+ }
64
+ ```
65
+
66
+ Here is the actual prompt to answer. Let's think step by step:
human_reference_dataset/iac-eval/evaluation/prompt-templates/few-shot.txt ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Here are a few examples:
2
+
3
+ Example prompt 1: Create an AWS RDS instance with randomly generated id and password
4
+ Example output 1:
5
+ ```hcl
6
+ resource "random_id" "suffix" {
7
+ byte_length = 4
8
+ }
9
+
10
+ resource "random_password" "db" {
11
+ length = 16
12
+ special = false
13
+ }
14
+
15
+ resource "aws_db_instance" "test" {
16
+ identifier = "metricbeat-test-${random_id.suffix.hex}"
17
+ allocated_storage = 20 // Gigabytes
18
+ engine = "mysql"
19
+ instance_class = "db.t2.micro"
20
+ db_name = "metricbeattest"
21
+ username = "foo"
22
+ password = random_password.db.result
23
+ skip_final_snapshot = true // Required for cleanup
24
+ }
25
+ ```
26
+
27
+ Example prompt 2: Create an 20GB MySQL instance on aws with randomly generated id and password
28
+ Example output 2:
29
+ ```hcl
30
+ resource "random_id" "suffix" {
31
+ byte_length = 4
32
+ }
33
+
34
+ resource "random_password" "db" {
35
+ length = 16
36
+ special = false
37
+ }
38
+
39
+ resource "aws_db_instance" "test" {
40
+ identifier = "metricbeat-test-${random_id.suffix.hex}"
41
+ allocated_storage = 20 // Gigabytes
42
+ engine = "mysql"
43
+ instance_class = "db.t2.micro"
44
+ db_name = "metricbeattest"
45
+ username = "foo"
46
+ password = random_password.db.result
47
+ skip_final_snapshot = true // Required for cleanup
48
+ }
49
+ ```
50
+
51
+ Example prompt 3: create a AWS EFS, and create a replica of an this created EFS file system using regional storage in us-west-3
52
+ Example output 3:
53
+ ```hcl
54
+ resource "aws_efs_file_system" "example" {}
55
+
56
+ resource "aws_efs_replication_configuration" "example" {
57
+ source_file_system_id = aws_efs_file_system.example.id
58
+
59
+ destination {
60
+ availability_zone_name = "us-west-2b"
61
+ kms_key_id = "1234abcd-12ab-34cd-56ef-1234567890ab"
62
+ }
63
+ }
64
+ ```
65
+
66
+ Here is the actual prompt to answer:
human_reference_dataset/iac-eval/evaluation/prompt-templates/multi-turn-system-prompt.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ You are TerraformAI, an AI agent that builds and deploys Cloud Infrastructure written in Terraform HCL. Given an incorrect Terraform program along with an error message, your task is to first describe the error in your own words, followed by a description of the fix you will apply, and ending with a single corrected Terraform HCL program. Make sure the configuration is deployable. Create IAM roles as needed. If variables are used, make sure default values are supplied.
human_reference_dataset/iac-eval/evaluation/prompt-templates/system-prompt.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ You are TerraformAI, an AI agent that builds and deploys Cloud Infrastructure written in Terraform HCL. Generate a description of the Terraform program you will define, followed by a single Terraform HCL program in response to each of my Instructions. Make sure the configuration is deployable. Create IAM roles as needed. If variables are used, make sure default values are supplied. Be sure to include a valid provider configuration within a valid region. Make sure there are no undeclared resources (e.g., as references) or variables, that is, all resources and variables needed in the configuration should be fully specified.
human_reference_dataset/iac-eval/evaluation/prompt_templates.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def CoT_prompt(question_prompt):
2
+ with open('prompt-templates/CoT.txt', 'r') as file:
3
+ data = file.read()
4
+ prompt = data + question_prompt # https://www.promptingguide.ai/techniques/cot#zero-shot-cot-prompting
5
+ return prompt
6
+
7
+ def FSP_prompt(question_prompt):
8
+ with open('prompt-templates/few-shot.txt', 'r') as file:
9
+ data = file.read()
10
+ prompt = data + question_prompt
11
+ return prompt
12
+
13
+ def RAG_prompt(context, question_prompt):
14
+ template = """
15
+ Here is some additional knowledge/context retrieved from Terraform documentation, that may (or may not) potentially help you answer the question:
16
+ {}
17
+
18
+ Here is the actual prompt to answer:
19
+ {}
20
+ """.format(context, question_prompt)
21
+ return template
22
+
23
+ def multi_turn_system_prompt():
24
+ with open('prompt-templates/multi-turn-system-prompt.txt', 'r') as file:
25
+ data = file.read()
26
+ return data
27
+
28
+ def multi_turn_plan_error_prompt(question_prompt, candidate_config, error_message):
29
+ prompt = """
30
+ Here is the original prompt:
31
+ {}
32
+
33
+ Here is the incorrect configuration:
34
+ {}
35
+
36
+ Here is the Terraform plan error message (potentially empty):
37
+ {}
38
+ """.format(question_prompt, candidate_config, error_message)
39
+ return prompt
40
+
41
+ def multi_turn_rego_error_prompt(question_prompt, candidate_config, rego_policy, error_message):
42
+ prompt = """
43
+ Here is the original prompt:
44
+ {}
45
+
46
+ Here is the incorrect configuration:
47
+ {}
48
+
49
+ Here is the Rego OPA policy associated with this configuration:
50
+ {}
51
+
52
+ Here is the Rego OPA policy error message:
53
+ {}
54
+ """.format(question_prompt, candidate_config, rego_policy, error_message)
55
+
56
+ return prompt
human_reference_dataset/iac-eval/evaluation/setup.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ ../setup.sh
human_reference_dataset/iac-eval/licenses/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ### Licenses
2
+ - CodeLlama: [LLama 2 Community License](https://github.com/facebookresearch/llama/blob/main/LICENSE)
3
+ - OpenAI: [Apache Software License](https://pypi.org/project/openai/)
4
+ - WizardCoder: [Apache License 2.0](https://github.com/nlpxucan/WizardLM/tree/main/WizardCoder)
5
+ - MagiCoder: [LLama 2 Community License](https://huggingface.co/ise-uiuc/Magicoder-S-CL-7B)
6
+ - Gemini: [Apache Software License](https://pypi.org/project/google-generativeai/)
human_reference_dataset/iac-eval/retriever/README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Retriever Setup
2
+
3
+ ## Requirements
4
+
5
+ Please make sure you have `iac-eval` conda environment activated and you are in the `retriever/` folder before executing any of the following commands.
6
+
7
+ Note: You can run `./setup.sh` for dependency check/setup and executing the following steps.
8
+
9
+ ## Download
10
+
11
+ ```shell
12
+ git clone https://github.com/hashicorp/terraform-provider-aws.git
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ The following script will:
18
+
19
+ 1. Ask LLM to generate a list of prompts to search for (``generate_prompt_for_index``).
20
+
21
+ 2. Use the generated list of prompts to query database (`query_documents`)
22
+
23
+ ```shell
24
+ python3 llama_index_retriever.py
25
+ ```
26
+
27
+ Note: 429 errors will cause retry and delay. This will take a while, but don't worry!
human_reference_dataset/iac-eval/retriever/llama_index_retriever.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import sys
4
+ from llama_index.llms.azure_openai import AzureOpenAI
5
+ from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding
6
+ from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
7
+ from llama_index.core import Settings
8
+ from llama_index.core import StorageContext, load_index_from_storage
9
+ from llama_index.core.node_parser import TokenTextSplitter
10
+ from llama_index.llms.openai import OpenAI
11
+ from llama_index.embeddings.openai import OpenAIEmbedding
12
+
13
+ class Retriever:
14
+ def __init__(self, stored_index = None, path = None, api_version="2023-03-15-preview"):
15
+ self.embed_model, self.llm = self.setup_api(api_version)
16
+ self.index = self.retrieve_documents(stored_index, path)
17
+
18
+ def setup_api(self, api_version):
19
+ if "OPENAI_API_KEY" not in os.environ:
20
+ api_key = input("Enter OpenAI API key:")
21
+ os.environ["OPENAI_API_KEY"] = api_key
22
+
23
+ api_key = os.environ["OPENAI_API_KEY"]
24
+
25
+ embed_model = OpenAIEmbedding(
26
+ model="text-embedding-ada-002", api_key=api_key
27
+ )
28
+
29
+ llm = OpenAI(api_key=api_key, model="gpt-3.5-turbo")
30
+
31
+ return embed_model, llm
32
+
33
+ def retrieve_documents(self, stored_index = None, path = None):
34
+ # if stored_index exists, load it
35
+ Settings.llm = self.llm
36
+ Settings.embed_model = self.embed_model
37
+ if os.path.exists(stored_index):
38
+ print("Loading index from storage")
39
+ storage_context = StorageContext.from_defaults(persist_dir=stored_index)
40
+ index = load_index_from_storage(storage_context)
41
+ else:
42
+ print("Building index from scratch")
43
+ nodes = self.read_docs(path)
44
+ index = self.build_index(nodes)
45
+ index.storage_context.persist(persist_dir=stored_index)
46
+ return index
47
+
48
+ def read_docs(self, path = "terraform-provider-aws/website/docs/r"):
49
+
50
+ documents = SimpleDirectoryReader(
51
+ path
52
+ ).load_data()
53
+
54
+ # parser = MarkdownNodeParser()
55
+
56
+ splitter = TokenTextSplitter(
57
+ chunk_size=400,
58
+ chunk_overlap=20,
59
+ separator=" ",
60
+ )
61
+ nodes = splitter.get_nodes_from_documents(documents)
62
+ print(f"Read {len(documents)} documents")
63
+ print(f"Extracted {len(nodes)} nodes")
64
+ return nodes
65
+
66
+ def build_index(self, nodes):
67
+ index = VectorStoreIndex(nodes)
68
+ return index
69
+
70
+ def generate_prompt_for_index(self, query, num_queries=10):
71
+ # The prompt is not necessary
72
+ QUERY_GEN_PROMPT = (
73
+ "You are a helpful assistant that generates multiple search queries based on a "
74
+ "single input query. Generate {num_queries} search queries, one on each line, "
75
+ "related to the following input query:\n"
76
+ "Query: {query}\n"
77
+ )
78
+ formatted_prompt = QUERY_GEN_PROMPT.format(num_queries=num_queries, query=query)
79
+
80
+ query_engine = self.index.as_query_engine()
81
+ response = query_engine.query(formatted_prompt)
82
+ questions = response.response.split('\n')
83
+
84
+ print(questions)
85
+ return questions
86
+
87
+ def query_documents(self, questions):
88
+ retriever = self.index.as_retriever()
89
+
90
+ context = set()
91
+ for q in questions:
92
+ if not isinstance(q, str) or q == "":
93
+ continue
94
+ nodes = retriever.retrieve(q)
95
+ context.add(nodes[0].text)
96
+ return context
97
+
98
+ if __name__ == "__main__":
99
+ retriever = Retriever(stored_index='aws-index', path='terraform-provider-aws/website/docs/r')
100
+ query = '''sets up a VPC with public and private subnets, multiple security groups for different components like master, worker, alert, API, standalone, and database services within an AWS region specified as "cn-north-1". It includes a 5.7, 50GB MySQL database instance within the VPC, accessible and secured by a designated security group.'''
101
+ questions = retriever.generate_prompt_for_index(query)
102
+ # questions = ['defines an AWS RDS option group named "option-group-pike" with major engine version 11, and use the sqlserver-ee engine. It should have options for "SQLSERVER_AUDIT" and "TDE" ', '', '1. How to create an AWS RDS option group with major engine version 11 and sqlserver-ee engine?', '2. What are the available options for an AWS RDS option group with major engine version 11 and sqlserver-ee engine?', '3. How to add the "SQLSERVER_AUDIT" option to an AWS RDS option group?', '4. How to add the "TDE" option to an AWS RDS option group?', '5. What is the option group description for an AWS RDS option group named "option-group-pike"?', '6. How to set the timezone option for an AWS RDS option group?', '7. How to set the IAM role ARN for the "SQLSERVER_BACKUP_RESTORE" option in an AWS RDS option group?', '8. What are the MariaDB options available for an AWS RDS option group?', '9. What are the Microsoft SQL Server options available for an AWS RDS option group?', '10. What are the MySQL options available for an AWS RDS option group?'] # this caused an error
103
+ context = retriever.query_documents(questions)
104
+ for i, c in enumerate(context):
105
+ print(f'Context {i}:')
106
+ print(c)
107
+
108
+
human_reference_dataset/iac-eval/retriever/setup.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -Eeuo pipefail
4
+
5
+ eval "$(command conda 'shell.bash' 'hook' 2> /dev/null)"
6
+
7
+ # Create the conda environment if it doesn't exist
8
+ if ! conda list --name iac-eval &> /dev/null; then
9
+ echo -e 'iac-eval conda environment not yet created. Creating the environment...'
10
+ conda env create -f ../environment.yml
11
+ fi
12
+
13
+ # Activate the conda environment
14
+ conda activate iac-eval
15
+
16
+ # Clone the git repository if it doesn't exist
17
+ if [ ! -d "terraform-provider-aws" ]; then
18
+ git clone https://github.com/hashicorp/terraform-provider-aws
19
+ fi
20
+
21
+ python3 llama_index_retriever.py
human_reference_dataset/iac-eval/setup.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -Eeuo pipefail
4
+
5
+ # This is basically what `conda init` adds to bashrc
6
+ eval "$(command conda 'shell.bash' 'hook' 2> /dev/null)"
7
+
8
+ # set -x
9
+
10
+ # Check if terraform is installed
11
+ if ! which terraform &> /dev/null; then
12
+ echo -e 'Make sure you have Terraform installed. Check README for how.' >&2
13
+ exit 1
14
+ fi
15
+
16
+ # Check if opa is installed
17
+ if ! which opa &> /dev/null; then
18
+ echo -e 'Make sure you have OPA installed. Check REAMD for how.' >&2
19
+ exit 1
20
+ fi
21
+
22
+ # Create the conda environment if it doesn't exist
23
+ if ! conda list --name iac-eval &> /dev/null; then
24
+ echo -e 'iac-eval conda environment not yet created. Creating the environment...'
25
+ conda env create -f environment.yml
26
+ fi
27
+
28
+ # Activate the conda environment
29
+ conda activate iac-eval
human_reference_dataset/iac-eval/templates/aws_chime_voice_connector/main.tf ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ resource "aws_chime_voice_connector" "test" {
2
+ name = "connector-test-1"
3
+ require_encryption = true
4
+ aws_region = "us-east-1"
5
+ tags = {
6
+ test-tag = "{insert tag}"
7
+ }
8
+ }
human_reference_dataset/iac-eval/templates/aws_chime_voice_connector/template.rego ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package aws_chime_voice_connector
2
+
3
+ # name - required
4
+ # require_encryption - required
5
+ # aws_region - optional
6
+ # tags - optional
7
+
8
+ import future.keywords.in
9
+
10
+ default chime_voice_connector_valid := false
11
+
12
+ chime_voice_connector_valid {
13
+ some chime_v_c in input.configuration.root_module.resources
14
+ chime_v_c.type == "aws_chime_voice_connector"
15
+
16
+ expressions := chime_v_c.expressions
17
+ # expressions.name == ""
18
+ is_boolean(expressions.require_encryption.constant_value)
19
+ # expressions.aws_region.constant_value == ""
20
+ # expressions.tags.constant_value.[tag name] == ""
21
+ }
human_reference_dataset/iac-eval/templates/aws_chime_voice_connector/tfplan.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.5.7",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_chime_voice_connector.test",
9
+ "mode": "managed",
10
+ "type": "aws_chime_voice_connector",
11
+ "name": "test",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "aws_region": "us-east-1",
16
+ "name": "connector-test-1",
17
+ "require_encryption": true,
18
+ "tags": {
19
+ "test-tag": "{insert tag}"
20
+ },
21
+ "tags_all": {
22
+ "test-tag": "{insert tag}"
23
+ }
24
+ },
25
+ "sensitive_values": {
26
+ "tags": {},
27
+ "tags_all": {}
28
+ }
29
+ }
30
+ ]
31
+ }
32
+ },
33
+ "resource_changes": [
34
+ {
35
+ "address": "aws_chime_voice_connector.test",
36
+ "mode": "managed",
37
+ "type": "aws_chime_voice_connector",
38
+ "name": "test",
39
+ "provider_name": "registry.terraform.io/hashicorp/aws",
40
+ "change": {
41
+ "actions": [
42
+ "create"
43
+ ],
44
+ "before": null,
45
+ "after": {
46
+ "aws_region": "us-east-1",
47
+ "name": "connector-test-1",
48
+ "require_encryption": true,
49
+ "tags": {
50
+ "test-tag": "{insert tag}"
51
+ },
52
+ "tags_all": {
53
+ "test-tag": "{insert tag}"
54
+ }
55
+ },
56
+ "after_unknown": {
57
+ "arn": true,
58
+ "id": true,
59
+ "outbound_host_name": true,
60
+ "tags": {},
61
+ "tags_all": {}
62
+ },
63
+ "before_sensitive": false,
64
+ "after_sensitive": {
65
+ "tags": {},
66
+ "tags_all": {}
67
+ }
68
+ }
69
+ }
70
+ ],
71
+ "configuration": {
72
+ "provider_config": {
73
+ "aws": {
74
+ "name": "aws",
75
+ "full_name": "registry.terraform.io/hashicorp/aws"
76
+ }
77
+ },
78
+ "root_module": {
79
+ "resources": [
80
+ {
81
+ "address": "aws_chime_voice_connector.test",
82
+ "mode": "managed",
83
+ "type": "aws_chime_voice_connector",
84
+ "name": "test",
85
+ "provider_config_key": "aws",
86
+ "expressions": {
87
+ "aws_region": {
88
+ "constant_value": "us-east-1"
89
+ },
90
+ "name": {
91
+ "constant_value": "connector-test-1"
92
+ },
93
+ "require_encryption": {
94
+ "constant_value": true
95
+ },
96
+ "tags": {
97
+ "constant_value": {
98
+ "test-tag": "{insert tag}"
99
+ }
100
+ }
101
+ },
102
+ "schema_version": 0
103
+ }
104
+ ]
105
+ }
106
+ },
107
+ "timestamp": "2023-12-05T17:15:38Z"
108
+ }
human_reference_dataset/iac-eval/templates/aws_iam_policy/main.tf ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ resource "aws_iam_policy" "policy" {
2
+ name = "test_policy"
3
+ path = "/"
4
+ description = "My test policy"
5
+
6
+ # Terraform's "jsonencode" function converts a
7
+ # Terraform expression result to valid JSON syntax.
8
+ policy = jsonencode({
9
+ Version = "2012-10-17"
10
+ Statement = [
11
+ {
12
+ Action = [
13
+ "ec2:Describe*",
14
+ ]
15
+ Effect = "Allow"
16
+ Resource = "*"
17
+ },
18
+ ]
19
+ })
20
+ }
human_reference_dataset/iac-eval/templates/aws_iam_policy/template.rego ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package aws_iam_policy
2
+
3
+ import future.keywords.in
4
+
5
+ # description - optional
6
+ # name - optional (conflicts with name_prefix)
7
+ # name_prefix - optional (conflicts with name)
8
+ # path - optional
9
+ # policy - required
10
+ # tags - optional
11
+
12
+ default iam_policy_valid := false
13
+
14
+ iam_policy_valid {
15
+ some iam_policy in input.resource_changes
16
+ iam_policy.type == "aws_iam_policy"
17
+
18
+ expressions := iam_policy.change.after
19
+
20
+ # expressions.name == "[name]" # if intended to be specific value
21
+
22
+ # expressions.name_prefix.constant_value == "[name_prefix]" # if intended to be specific value
23
+
24
+ # expressions.path.constant_value == "[path]" # if intended to be specific value
25
+
26
+ # TODO: How to verify if policies are valid
27
+ # expressions.policy
28
+
29
+ # expressions.tags.[tag name] == "[tag value]" # if a tag is intended to be a specific value
30
+ }
human_reference_dataset/iac-eval/templates/aws_iam_policy/tfplan.json ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.5.7",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_iam_policy.policy",
9
+ "mode": "managed",
10
+ "type": "aws_iam_policy",
11
+ "name": "policy",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "description": "My test policy",
16
+ "name": "test_policy",
17
+ "path": "/",
18
+ "policy": "{\"Statement\":[{\"Action\":[\"ec2:Describe*\"],\"Effect\":\"Allow\",\"Resource\":\"*\"}],\"Version\":\"2012-10-17\"}",
19
+ "tags": null
20
+ },
21
+ "sensitive_values": {
22
+ "tags_all": {}
23
+ }
24
+ }
25
+ ]
26
+ }
27
+ },
28
+ "resource_changes": [
29
+ {
30
+ "address": "aws_iam_policy.policy",
31
+ "mode": "managed",
32
+ "type": "aws_iam_policy",
33
+ "name": "policy",
34
+ "provider_name": "registry.terraform.io/hashicorp/aws",
35
+ "change": {
36
+ "actions": [
37
+ "create"
38
+ ],
39
+ "before": null,
40
+ "after": {
41
+ "description": "My test policy",
42
+ "name": "test_policy",
43
+ "path": "/",
44
+ "policy": "{\"Statement\":[{\"Action\":[\"ec2:Describe*\"],\"Effect\":\"Allow\",\"Resource\":\"*\"}],\"Version\":\"2012-10-17\"}",
45
+ "tags": null
46
+ },
47
+ "after_unknown": {
48
+ "arn": true,
49
+ "id": true,
50
+ "name_prefix": true,
51
+ "policy_id": true,
52
+ "tags_all": true
53
+ },
54
+ "before_sensitive": false,
55
+ "after_sensitive": {
56
+ "tags_all": {}
57
+ }
58
+ }
59
+ }
60
+ ],
61
+ "configuration": {
62
+ "provider_config": {
63
+ "aws": {
64
+ "name": "aws",
65
+ "full_name": "registry.terraform.io/hashicorp/aws"
66
+ }
67
+ },
68
+ "root_module": {
69
+ "resources": [
70
+ {
71
+ "address": "aws_iam_policy.policy",
72
+ "mode": "managed",
73
+ "type": "aws_iam_policy",
74
+ "name": "policy",
75
+ "provider_config_key": "aws",
76
+ "expressions": {
77
+ "description": {
78
+ "constant_value": "My test policy"
79
+ },
80
+ "name": {
81
+ "constant_value": "test_policy"
82
+ },
83
+ "path": {
84
+ "constant_value": "/"
85
+ },
86
+ "policy": {}
87
+ },
88
+ "schema_version": 0
89
+ }
90
+ ]
91
+ }
92
+ },
93
+ "timestamp": "2023-12-05T19:48:13Z"
94
+ }
human_reference_dataset/iac-eval/templates/aws_iam_role/main.tf ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ resource "aws_iam_role" "test_role" {
2
+ name = "test_role"
3
+ description="test role for templating"
4
+ force_detach_policies = false
5
+ max_session_duration=3600
6
+ path="/"
7
+
8
+ # Terraform's "jsonencode" function converts a
9
+ # Terraform expression result to valid JSON syntax.
10
+ assume_role_policy = jsonencode({
11
+ Version = "2012-10-17"
12
+ Statement = [
13
+ {
14
+ Action = "sts:AssumeRole"
15
+ Effect = "Allow"
16
+ Sid = ""
17
+ Principal = {
18
+ Service = "ec2.amazonaws.com"
19
+ }
20
+ },
21
+ ]
22
+ })
23
+
24
+ tags = {
25
+ tag-key = "tag-value"
26
+ }
27
+ }
28
+
human_reference_dataset/iac-eval/templates/aws_iam_role/template.rego ADDED
File without changes
human_reference_dataset/iac-eval/templates/aws_iam_role/tfplan.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.5.7",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_iam_role.test_role",
9
+ "mode": "managed",
10
+ "type": "aws_iam_role",
11
+ "name": "test_role",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "assume_role_policy": "{\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Sid\":\"\"}],\"Version\":\"2012-10-17\"}",
16
+ "description": "test role for templating",
17
+ "force_detach_policies": false,
18
+ "max_session_duration": 3600,
19
+ "name": "test_role",
20
+ "path": "/",
21
+ "permissions_boundary": null,
22
+ "tags": {
23
+ "tag-key": "tag-value"
24
+ },
25
+ "tags_all": {
26
+ "tag-key": "tag-value"
27
+ }
28
+ },
29
+ "sensitive_values": {
30
+ "inline_policy": [],
31
+ "managed_policy_arns": [],
32
+ "tags": {},
33
+ "tags_all": {}
34
+ }
35
+ }
36
+ ]
37
+ }
38
+ },
39
+ "resource_changes": [
40
+ {
41
+ "address": "aws_iam_role.test_role",
42
+ "mode": "managed",
43
+ "type": "aws_iam_role",
44
+ "name": "test_role",
45
+ "provider_name": "registry.terraform.io/hashicorp/aws",
46
+ "change": {
47
+ "actions": [
48
+ "create"
49
+ ],
50
+ "before": null,
51
+ "after": {
52
+ "assume_role_policy": "{\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Sid\":\"\"}],\"Version\":\"2012-10-17\"}",
53
+ "description": "test role for templating",
54
+ "force_detach_policies": false,
55
+ "max_session_duration": 3600,
56
+ "name": "test_role",
57
+ "path": "/",
58
+ "permissions_boundary": null,
59
+ "tags": {
60
+ "tag-key": "tag-value"
61
+ },
62
+ "tags_all": {
63
+ "tag-key": "tag-value"
64
+ }
65
+ },
66
+ "after_unknown": {
67
+ "arn": true,
68
+ "create_date": true,
69
+ "id": true,
70
+ "inline_policy": true,
71
+ "managed_policy_arns": true,
72
+ "name_prefix": true,
73
+ "tags": {},
74
+ "tags_all": {},
75
+ "unique_id": true
76
+ },
77
+ "before_sensitive": false,
78
+ "after_sensitive": {
79
+ "inline_policy": [],
80
+ "managed_policy_arns": [],
81
+ "tags": {},
82
+ "tags_all": {}
83
+ }
84
+ }
85
+ }
86
+ ],
87
+ "configuration": {
88
+ "provider_config": {
89
+ "aws": {
90
+ "name": "aws",
91
+ "full_name": "registry.terraform.io/hashicorp/aws"
92
+ }
93
+ },
94
+ "root_module": {
95
+ "resources": [
96
+ {
97
+ "address": "aws_iam_role.test_role",
98
+ "mode": "managed",
99
+ "type": "aws_iam_role",
100
+ "name": "test_role",
101
+ "provider_config_key": "aws",
102
+ "expressions": {
103
+ "assume_role_policy": {},
104
+ "description": {
105
+ "constant_value": "test role for templating"
106
+ },
107
+ "force_detach_policies": {
108
+ "constant_value": false
109
+ },
110
+ "max_session_duration": {
111
+ "constant_value": 3600
112
+ },
113
+ "name": {
114
+ "constant_value": "test_role"
115
+ },
116
+ "path": {
117
+ "constant_value": "/"
118
+ },
119
+ "tags": {
120
+ "constant_value": {
121
+ "tag-key": "tag-value"
122
+ }
123
+ }
124
+ },
125
+ "schema_version": 0
126
+ }
127
+ ]
128
+ }
129
+ },
130
+ "timestamp": "2023-12-20T16:39:10Z"
131
+ }
human_reference_dataset/iac-eval/templates/aws_iam_user/main.tf ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ resource "aws_iam_user" "example" {
2
+ name = "example_user"
3
+ path = "/system/"
4
+ force_destroy = false
5
+
6
+ tags = {
7
+ tag-key = "tag-value"
8
+ }
9
+ }
human_reference_dataset/iac-eval/templates/aws_iam_user/template.rego ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package aws_iam_user
2
+
3
+ import future.keywords.in
4
+
5
+ # name - required
6
+ # path - optional
7
+ # permissions_boundary - optional
8
+ # force_destroy - optional
9
+ # tags - optional
10
+
11
+ default iam_user_valid := false
12
+
13
+ iam_user_valid {
14
+ some iam_user in input.configuration.root_module.resources
15
+ iam_user.type == "aws_iam_user"
16
+
17
+ expressions := iam_user.expressions
18
+
19
+ # expressions.name == "[name]" # if intended to be specific value
20
+
21
+ # expressions.path.constant_value == "[path]" # if intended to be specific value
22
+
23
+ # TODO: permissions_boundary
24
+
25
+ # expressions.force_destroy.constant_value == [true/false]
26
+
27
+ # expressions.tags.[tag name] == "[tag value]" # if a tag is intended to be a specific value
28
+ }
human_reference_dataset/iac-eval/templates/aws_iam_user/tfplan.json ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.5.7",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_iam_user.example",
9
+ "mode": "managed",
10
+ "type": "aws_iam_user",
11
+ "name": "example",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "force_destroy": false,
16
+ "name": "example_user",
17
+ "path": "/system/",
18
+ "permissions_boundary": null,
19
+ "tags": {
20
+ "tag-key": "tag-value"
21
+ },
22
+ "tags_all": {
23
+ "tag-key": "tag-value"
24
+ }
25
+ },
26
+ "sensitive_values": {
27
+ "tags": {},
28
+ "tags_all": {}
29
+ }
30
+ }
31
+ ]
32
+ }
33
+ },
34
+ "resource_changes": [
35
+ {
36
+ "address": "aws_iam_user.example",
37
+ "mode": "managed",
38
+ "type": "aws_iam_user",
39
+ "name": "example",
40
+ "provider_name": "registry.terraform.io/hashicorp/aws",
41
+ "change": {
42
+ "actions": [
43
+ "create"
44
+ ],
45
+ "before": null,
46
+ "after": {
47
+ "force_destroy": false,
48
+ "name": "example_user",
49
+ "path": "/system/",
50
+ "permissions_boundary": null,
51
+ "tags": {
52
+ "tag-key": "tag-value"
53
+ },
54
+ "tags_all": {
55
+ "tag-key": "tag-value"
56
+ }
57
+ },
58
+ "after_unknown": {
59
+ "arn": true,
60
+ "id": true,
61
+ "tags": {},
62
+ "tags_all": {},
63
+ "unique_id": true
64
+ },
65
+ "before_sensitive": false,
66
+ "after_sensitive": {
67
+ "tags": {},
68
+ "tags_all": {}
69
+ }
70
+ }
71
+ }
72
+ ],
73
+ "configuration": {
74
+ "provider_config": {
75
+ "aws": {
76
+ "name": "aws",
77
+ "full_name": "registry.terraform.io/hashicorp/aws"
78
+ }
79
+ },
80
+ "root_module": {
81
+ "resources": [
82
+ {
83
+ "address": "aws_iam_user.example",
84
+ "mode": "managed",
85
+ "type": "aws_iam_user",
86
+ "name": "example",
87
+ "provider_config_key": "aws",
88
+ "expressions": {
89
+ "force_destroy": {
90
+ "constant_value": false
91
+ },
92
+ "name": {
93
+ "constant_value": "example_user"
94
+ },
95
+ "path": {
96
+ "constant_value": "/system/"
97
+ },
98
+ "tags": {
99
+ "constant_value": {
100
+ "tag-key": "tag-value"
101
+ }
102
+ }
103
+ },
104
+ "schema_version": 0
105
+ }
106
+ ]
107
+ }
108
+ },
109
+ "timestamp": "2023-12-05T20:00:49Z"
110
+ }
human_reference_dataset/iac-eval/templates/aws_lb/template.rego ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package terraform.validation
2
+
3
+ default is_valid_configuration = false
4
+
5
+ # has one asw_lb resource
6
+ is_valid_lb {
7
+ is_valid_app_lb
8
+ has_valid_subnet
9
+ }
10
+
11
+ is_valid_app_lb {
12
+ resource := input.planned_values.root_module.resources[_]
13
+ resource.type == "aws_lb"
14
+ resource.values.load_balancer_type == "application"
15
+ }
16
+
17
+ has_valid_subnet {
18
+ resource := input.planned_values.root_module.resources[_]
19
+ resource.type == "aws_lb"
20
+ resource.values.subnet_mapping != null
21
+ }
22
+
23
+ has_valid_subnet {
24
+ resource := input.configuration.root_module.resources[_]
25
+ resource.type == "aws_lb"
26
+ resource.expressions.subnets
27
+ }
28
+
29
+ # has one vpc resource
30
+ is_valid_vpc {
31
+ have_required_vpc_argument
32
+ }
33
+
34
+ have_required_vpc_argument {
35
+ resource := input.configuration.root_module.resources[_]
36
+ resource.type == "aws_vpc"
37
+ resource.expressions.cidr_block.constant_value != null
38
+ }
39
+
40
+ have_required_vpc_argument {
41
+ resource := input.configuration.root_module.resources[_]
42
+ resource.type == "aws_vpc"
43
+ resource.expressions.ipv4_ipam_pool_id.constant_value != null
44
+ }
45
+
46
+ # has valid subnet
47
+ is_valid_subnet {
48
+ resource := input.configuration.root_module.resources[_]
49
+ resource.type == "aws_subnet"
50
+ resource.expressions.vpc_id != null
51
+ have_required_subnet_argument
52
+ }
53
+
54
+ have_required_subnet_argument {
55
+ resource := input.configuration.root_module.resources[_]
56
+ resource.type == "aws_subnet"
57
+ resource.expressions.cidr_block != null
58
+ }
59
+
60
+ have_required_subnet_argument {
61
+ resource := input.configuration.root_module.resources[_]
62
+ resource.type == "aws_subnet"
63
+ resource.expressions.ipv6_cider_block != null
64
+ }
65
+
66
+ # Validate aws_lb_listener with the required arguments
67
+ is_valid_lb_listener {
68
+ resource := input.configuration.root_module.resources[_]
69
+ resource.type == "aws_lb_listener"
70
+ resource.expressions.load_balancer_arn
71
+ has_valid_default_action
72
+ }
73
+ # if type is forward, must have target_group_arn
74
+ has_valid_default_action {
75
+ resource := input.configuration.root_module.resources[_]
76
+ resource.type == "aws_lb_listener"
77
+ resource.expressions.default_action[0].type.constant_value == "forward"
78
+ resource.expressions.default_action[0].target_group_arn != null
79
+ }
80
+
81
+ has_valid_default_action {
82
+ resource := input.configuration.root_module.resources[_]
83
+ resource.type == "aws_lb_listener"
84
+ resource.expressions.default_action[0].type.constant_value != "forward"
85
+ }
86
+
87
+ # if target type is instance, ip, or alb, should have protocol, port, and vpc_id
88
+ is_valid_lb_target_group {
89
+ resources := input.planned_values.root_module.resources[_]
90
+ resources.type == "aws_lb_target_group"
91
+ valid_type := {"instance", "ip", "alb"}
92
+ type := resources.values.target_type
93
+ valid_type[type]
94
+
95
+ resource := input.configuration.root_module.resources[_]
96
+ resource.type == "aws_lb_target_group"
97
+ resource.expressions.port != null
98
+ resource.expressions.protocol != null
99
+ resource.expressions.vpc_id != null
100
+ }
101
+
102
+ is_valid_lb_target_group {
103
+ resource := input.planned_values.root_module.resources[_]
104
+ resource.type == "aws_lb_listener"
105
+ resource.values.target_type == "lambda"
106
+ }
107
+
108
+ # Validate aws_lb_target_group_attachment with the required arguments
109
+ is_valid_lb_target_group_attachment {
110
+ resource := input.configuration.root_module.resources[_]
111
+ resource.type == "aws_lb_target_group_attachment"
112
+ resource.expressions.target_group_arn
113
+ resource.expressions.target_id
114
+ }
115
+
116
+ # Validate at least one aws_instance with the required arguments
117
+ is_valid_instance {
118
+ count(valid_instances) > 0
119
+ }
120
+
121
+ valid_instances[instance] {
122
+ instance := input.configuration.root_module.resources[_]
123
+ instance.type == "aws_instance"
124
+ requited_argument(instance)
125
+ }
126
+
127
+ requited_argument(instance) {
128
+ instance.expressions.launch_template != null
129
+ }
130
+
131
+ requited_argument(instance) {
132
+ instance.expressions.ami != null
133
+ instance.expressions.instance_type != null
134
+ }
135
+
136
+ # Aggregate validation
137
+ is_valid_configuration {
138
+ is_valid_vpc
139
+ is_valid_subnet
140
+ is_valid_lb
141
+ is_valid_lb_listener
142
+ is_valid_lb_target_group_attachment
143
+ is_valid_lb_target_group
144
+ is_valid_instance
145
+ }
146
+
147
+
human_reference_dataset/iac-eval/templates/aws_neptune_cluster/main.tf ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ resource "aws_neptune_cluster" "default" {
2
+ allow_major_version_upgrade = false
3
+ apply_immediately = true
4
+ availability_zones = [ "us-east-1a" ]
5
+ backup_retention_period = 2
6
+ cluster_identifier = "neptune-cluster-demo"
7
+ # cluster_identifier_prefix = "cluster-prefix" # CONFLICTS WITH `cluster_identifier`
8
+ copy_tags_to_snapshot = false
9
+ enable_cloudwatch_logs_exports = [ "audit", "slowquery" ]
10
+ engine = "neptune"
11
+ engine_version = "1.2.1.0"
12
+ final_snapshot_identifier = "cluster-final-snapshot"
13
+ # global_cluster_identifer = aws_neptune_global_cluster.<resource name>.id
14
+ # iam_roles = [ aws_iam_role.<resource name>.arn ]
15
+ iam_database_authentication_enabled = false
16
+ # kms_key_arn = aws_kms_key.<resource name>.arn # REQUIRES `storage_encrypted = true`
17
+ neptune_subnet_group_name = aws_neptune_subnet_group.example_subnet_group.id
18
+ neptune_cluster_parameter_group_name = aws_neptune_cluster_parameter_group.example_cluster_parameter_group.id
19
+ # neptune_instance_parameter_group_name = aws_neptune_instance_parameter_group.<resource name>.id
20
+ preferred_backup_window = "07:00-09:00"
21
+ port = 8182
22
+ # replication_source_identifier = aws_neptune_cluster.<resource name>.arn
23
+ skip_final_snapshot = true
24
+ # snapshot_identifier = aws_neptune_cluster_snapshot.<resource name>.arn
25
+ storage_encrypted = false
26
+ tags = {
27
+ test-tag = "insert tag"
28
+ }
29
+ # vpc_security_group_ids = [ aws_security_group.<resource name>.id ]
30
+ deletion_protection = false
31
+ # serverless_v2_scaling_configuration { }
32
+ }
33
+
34
+ resource "aws_neptune_cluster_parameter_group" "example_cluster_parameter_group" {
35
+ family = "neptune1.2" # neptune1 is also valid but will not work with engines version 1.2.0.0 and higher
36
+ name = "example"
37
+ # name_prefix = "example-prefix" # CONFLICTS WTIH `name`
38
+ description = "terraform neptune cluster parameter group"
39
+ parameter {
40
+ name = "neptune_enable_audit_log"
41
+ value = 1
42
+ }
43
+ tags = {
44
+ Name = "My neptune cluster parameter group"
45
+ }
46
+ }
47
+
48
+ resource "aws_neptune_subnet_group" "example_subnet_group" {
49
+ name = "example"
50
+ # name_prefix = "example-prefix" # CONFLICTS WTIH `name`
51
+ subnet_ids = [aws_subnet.subnet1.id, aws_subnet.subnet2.id]
52
+ description = "terraform neptune subnet group"
53
+ tags = {
54
+ Name = "My neptune subnet group"
55
+ }
56
+ }
57
+
58
+ resource "aws_vpc" "example_vpc" {
59
+ cidr_block = "10.0.0.0/16"
60
+ }
61
+
62
+ resource "aws_subnet" "subnet1" {
63
+ vpc_id = aws_vpc.example_vpc.id
64
+ cidr_block = "10.0.1.0/24"
65
+ }
66
+
67
+ resource "aws_subnet" "subnet2" {
68
+ vpc_id = aws_vpc.example_vpc.id
69
+ cidr_block = "10.0.2.0/24"
70
+ }
human_reference_dataset/iac-eval/templates/aws_neptune_cluster/template.rego ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package aws_neptune_cluster
2
+
3
+ import future.keywords.in
4
+
5
+ # all attributes are technically optional
6
+ # tags - may only contain unicode letters, digits, whitespace, or one of these symbols: _ . : / = + - @
7
+ # availability_zone_allowed_values := {"us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d", "us-east-1e", "us-east-1f", ...}
8
+
9
+ default neptune_cluster_valid := false
10
+ default cluster_parameter_group_valid := false
11
+
12
+ neptune_cluster_valid {
13
+ some cluster in input.configuration.root_module.resources
14
+ cluster.type == "aws_neptune_cluster"
15
+
16
+ # cluster.expressions.allow_major_version_upgrade.constant_value == true/false # if intended to be specific value
17
+ # is_boolean(cluster.expressions.allow_major_version_upgrade.constant_value) # if intended to be defined but value doesn't matter
18
+
19
+ # cluster.expressions.apply_immediately.constant_value == true/false # if intended to be specific value
20
+ # is_boolean(cluster.expressions.apply_immediately.constant_value) # if intended to be defined but value doesn't matter
21
+
22
+ # some availability_zone in cluster.expressions.availability_zones.constant_value
23
+ # availability_zone == "" # if intended to be specific value
24
+ # availability_zone in availability_zone_allowed_values # if intended to be defined but value doesn't matter
25
+
26
+ # cluster_parameter_group_valid
27
+
28
+ # TODO: ALL OTHER ATTRIBUTES (they don't seem that important)
29
+ }
30
+
31
+ cluster_parameter_group_valid {
32
+ some cluster in input.configuration.root_module.resources
33
+ cluster.type == "aws_neptune_cluster"
34
+
35
+ some cluster_parameter_group in input.configuration.root_module.resources
36
+ cluster_parameter_group.type == "aws_neptune_cluster_parameter_group"
37
+ cluster_parameter_group.address in cluster.expressions.neptune_cluster_parameter_group_name.references
38
+
39
+ # See for more info: https://docs.aws.amazon.com/neptune/latest/userguide/parameter-groups.html
40
+ cluster.expressions.engine_version.constant_value < "1.2.0.0"
41
+ cluster_parameter_group.expressions.family.constant_value == "neptune1"
42
+ }
43
+
44
+ cluster_parameter_group_valid {
45
+ some cluster in input.configuration.root_module.resources
46
+ cluster.type == "aws_neptune_cluster"
47
+
48
+ some cluster_parameter_group in input.configuration.root_module.resources
49
+ cluster_parameter_group.type == "aws_neptune_cluster_parameter_group"
50
+ cluster_parameter_group.address in cluster.expressions.neptune_cluster_parameter_group_name.references
51
+
52
+ # See for more info: https://docs.aws.amazon.com/neptune/latest/userguide/parameter-groups.html
53
+ cluster.expressions.engine_version.constant_value >= "1.2.0.0"
54
+ cluster_parameter_group.expressions.family.constant_value == "neptune1.2"
55
+ }
56
+
57
+ cluster_parameter_group_valid {
58
+ some cluster in input.configuration.root_module.resources
59
+ cluster.type == "aws_neptune_cluster"
60
+
61
+ some cluster_parameter_group in input.configuration.root_module.resources
62
+ cluster_parameter_group.type == "aws_neptune_cluster_parameter_group"
63
+ cluster_parameter_group.address in cluster.expressions.neptune_cluster_parameter_group_name.references
64
+
65
+ # See for more info: https://docs.aws.amazon.com/neptune/latest/userguide/parameter-groups.html
66
+ not cluster.expressions.engine_version.constant_value # defaults as latest version
67
+ cluster_parameter_group.expressions.family.constant_value == "neptune1.2"
68
+ }
human_reference_dataset/iac-eval/templates/aws_neptune_cluster/tfplan.json ADDED
@@ -0,0 +1,749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.6.6",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_neptune_cluster.default",
9
+ "mode": "managed",
10
+ "type": "aws_neptune_cluster",
11
+ "name": "default",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "allow_major_version_upgrade": false,
16
+ "apply_immediately": true,
17
+ "availability_zones": [
18
+ "us-east-1a"
19
+ ],
20
+ "backup_retention_period": 2,
21
+ "cluster_identifier": "neptune-cluster-demo",
22
+ "copy_tags_to_snapshot": false,
23
+ "deletion_protection": false,
24
+ "enable_cloudwatch_logs_exports": [
25
+ "audit",
26
+ "slowquery"
27
+ ],
28
+ "engine": "neptune",
29
+ "engine_version": "1.2.1.0",
30
+ "final_snapshot_identifier": "cluster-final-snapshot",
31
+ "global_cluster_identifier": null,
32
+ "iam_database_authentication_enabled": false,
33
+ "iam_roles": null,
34
+ "neptune_instance_parameter_group_name": null,
35
+ "port": 8182,
36
+ "preferred_backup_window": "07:00-09:00",
37
+ "replication_source_identifier": null,
38
+ "serverless_v2_scaling_configuration": [],
39
+ "skip_final_snapshot": true,
40
+ "snapshot_identifier": null,
41
+ "storage_encrypted": false,
42
+ "tags": {
43
+ "test-tag": "insert tag"
44
+ },
45
+ "tags_all": {
46
+ "test-tag": "insert tag"
47
+ },
48
+ "timeouts": null
49
+ },
50
+ "sensitive_values": {
51
+ "availability_zones": [
52
+ false
53
+ ],
54
+ "cluster_members": [],
55
+ "enable_cloudwatch_logs_exports": [
56
+ false,
57
+ false
58
+ ],
59
+ "serverless_v2_scaling_configuration": [],
60
+ "tags": {},
61
+ "tags_all": {},
62
+ "vpc_security_group_ids": []
63
+ }
64
+ },
65
+ {
66
+ "address": "aws_neptune_cluster_parameter_group.example_cluster_parameter_group",
67
+ "mode": "managed",
68
+ "type": "aws_neptune_cluster_parameter_group",
69
+ "name": "example_cluster_parameter_group",
70
+ "provider_name": "registry.terraform.io/hashicorp/aws",
71
+ "schema_version": 0,
72
+ "values": {
73
+ "description": "terraform neptune cluster parameter group",
74
+ "family": "neptune1.2",
75
+ "name": "example",
76
+ "parameter": [
77
+ {
78
+ "apply_method": "pending-reboot",
79
+ "name": "neptune_enable_audit_log",
80
+ "value": "1"
81
+ }
82
+ ],
83
+ "tags": {
84
+ "Name": "My neptune cluster parameter group"
85
+ },
86
+ "tags_all": {
87
+ "Name": "My neptune cluster parameter group"
88
+ }
89
+ },
90
+ "sensitive_values": {
91
+ "parameter": [
92
+ {}
93
+ ],
94
+ "tags": {},
95
+ "tags_all": {}
96
+ }
97
+ },
98
+ {
99
+ "address": "aws_neptune_subnet_group.example_subnet_group",
100
+ "mode": "managed",
101
+ "type": "aws_neptune_subnet_group",
102
+ "name": "example_subnet_group",
103
+ "provider_name": "registry.terraform.io/hashicorp/aws",
104
+ "schema_version": 0,
105
+ "values": {
106
+ "description": "terraform neptune subnet group",
107
+ "name": "example",
108
+ "tags": {
109
+ "Name": "My neptune subnet group"
110
+ },
111
+ "tags_all": {
112
+ "Name": "My neptune subnet group"
113
+ }
114
+ },
115
+ "sensitive_values": {
116
+ "subnet_ids": [],
117
+ "tags": {},
118
+ "tags_all": {}
119
+ }
120
+ },
121
+ {
122
+ "address": "aws_subnet.subnet1",
123
+ "mode": "managed",
124
+ "type": "aws_subnet",
125
+ "name": "subnet1",
126
+ "provider_name": "registry.terraform.io/hashicorp/aws",
127
+ "schema_version": 1,
128
+ "values": {
129
+ "assign_ipv6_address_on_creation": false,
130
+ "cidr_block": "10.0.1.0/24",
131
+ "customer_owned_ipv4_pool": null,
132
+ "enable_dns64": false,
133
+ "enable_lni_at_device_index": null,
134
+ "enable_resource_name_dns_a_record_on_launch": false,
135
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
136
+ "ipv6_cidr_block": null,
137
+ "ipv6_native": false,
138
+ "map_customer_owned_ip_on_launch": null,
139
+ "map_public_ip_on_launch": false,
140
+ "outpost_arn": null,
141
+ "tags": null,
142
+ "timeouts": null
143
+ },
144
+ "sensitive_values": {
145
+ "tags_all": {}
146
+ }
147
+ },
148
+ {
149
+ "address": "aws_subnet.subnet2",
150
+ "mode": "managed",
151
+ "type": "aws_subnet",
152
+ "name": "subnet2",
153
+ "provider_name": "registry.terraform.io/hashicorp/aws",
154
+ "schema_version": 1,
155
+ "values": {
156
+ "assign_ipv6_address_on_creation": false,
157
+ "cidr_block": "10.0.2.0/24",
158
+ "customer_owned_ipv4_pool": null,
159
+ "enable_dns64": false,
160
+ "enable_lni_at_device_index": null,
161
+ "enable_resource_name_dns_a_record_on_launch": false,
162
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
163
+ "ipv6_cidr_block": null,
164
+ "ipv6_native": false,
165
+ "map_customer_owned_ip_on_launch": null,
166
+ "map_public_ip_on_launch": false,
167
+ "outpost_arn": null,
168
+ "tags": null,
169
+ "timeouts": null
170
+ },
171
+ "sensitive_values": {
172
+ "tags_all": {}
173
+ }
174
+ },
175
+ {
176
+ "address": "aws_vpc.example_vpc",
177
+ "mode": "managed",
178
+ "type": "aws_vpc",
179
+ "name": "example_vpc",
180
+ "provider_name": "registry.terraform.io/hashicorp/aws",
181
+ "schema_version": 1,
182
+ "values": {
183
+ "assign_generated_ipv6_cidr_block": null,
184
+ "cidr_block": "10.0.0.0/16",
185
+ "enable_dns_support": true,
186
+ "instance_tenancy": "default",
187
+ "ipv4_ipam_pool_id": null,
188
+ "ipv4_netmask_length": null,
189
+ "ipv6_ipam_pool_id": null,
190
+ "ipv6_netmask_length": null,
191
+ "tags": null
192
+ },
193
+ "sensitive_values": {
194
+ "tags_all": {}
195
+ }
196
+ }
197
+ ]
198
+ }
199
+ },
200
+ "resource_changes": [
201
+ {
202
+ "address": "aws_neptune_cluster.default",
203
+ "mode": "managed",
204
+ "type": "aws_neptune_cluster",
205
+ "name": "default",
206
+ "provider_name": "registry.terraform.io/hashicorp/aws",
207
+ "change": {
208
+ "actions": [
209
+ "create"
210
+ ],
211
+ "before": null,
212
+ "after": {
213
+ "allow_major_version_upgrade": false,
214
+ "apply_immediately": true,
215
+ "availability_zones": [
216
+ "us-east-1a"
217
+ ],
218
+ "backup_retention_period": 2,
219
+ "cluster_identifier": "neptune-cluster-demo",
220
+ "copy_tags_to_snapshot": false,
221
+ "deletion_protection": false,
222
+ "enable_cloudwatch_logs_exports": [
223
+ "audit",
224
+ "slowquery"
225
+ ],
226
+ "engine": "neptune",
227
+ "engine_version": "1.2.1.0",
228
+ "final_snapshot_identifier": "cluster-final-snapshot",
229
+ "global_cluster_identifier": null,
230
+ "iam_database_authentication_enabled": false,
231
+ "iam_roles": null,
232
+ "neptune_instance_parameter_group_name": null,
233
+ "port": 8182,
234
+ "preferred_backup_window": "07:00-09:00",
235
+ "replication_source_identifier": null,
236
+ "serverless_v2_scaling_configuration": [],
237
+ "skip_final_snapshot": true,
238
+ "snapshot_identifier": null,
239
+ "storage_encrypted": false,
240
+ "tags": {
241
+ "test-tag": "insert tag"
242
+ },
243
+ "tags_all": {
244
+ "test-tag": "insert tag"
245
+ },
246
+ "timeouts": null
247
+ },
248
+ "after_unknown": {
249
+ "arn": true,
250
+ "availability_zones": [
251
+ false
252
+ ],
253
+ "cluster_identifier_prefix": true,
254
+ "cluster_members": true,
255
+ "cluster_resource_id": true,
256
+ "enable_cloudwatch_logs_exports": [
257
+ false,
258
+ false
259
+ ],
260
+ "endpoint": true,
261
+ "hosted_zone_id": true,
262
+ "id": true,
263
+ "kms_key_arn": true,
264
+ "neptune_cluster_parameter_group_name": true,
265
+ "neptune_subnet_group_name": true,
266
+ "preferred_maintenance_window": true,
267
+ "reader_endpoint": true,
268
+ "serverless_v2_scaling_configuration": [],
269
+ "tags": {},
270
+ "tags_all": {},
271
+ "vpc_security_group_ids": true
272
+ },
273
+ "before_sensitive": false,
274
+ "after_sensitive": {
275
+ "availability_zones": [
276
+ false
277
+ ],
278
+ "cluster_members": [],
279
+ "enable_cloudwatch_logs_exports": [
280
+ false,
281
+ false
282
+ ],
283
+ "serverless_v2_scaling_configuration": [],
284
+ "tags": {},
285
+ "tags_all": {},
286
+ "vpc_security_group_ids": []
287
+ }
288
+ }
289
+ },
290
+ {
291
+ "address": "aws_neptune_cluster_parameter_group.example_cluster_parameter_group",
292
+ "mode": "managed",
293
+ "type": "aws_neptune_cluster_parameter_group",
294
+ "name": "example_cluster_parameter_group",
295
+ "provider_name": "registry.terraform.io/hashicorp/aws",
296
+ "change": {
297
+ "actions": [
298
+ "create"
299
+ ],
300
+ "before": null,
301
+ "after": {
302
+ "description": "terraform neptune cluster parameter group",
303
+ "family": "neptune1.2",
304
+ "name": "example",
305
+ "parameter": [
306
+ {
307
+ "apply_method": "pending-reboot",
308
+ "name": "neptune_enable_audit_log",
309
+ "value": "1"
310
+ }
311
+ ],
312
+ "tags": {
313
+ "Name": "My neptune cluster parameter group"
314
+ },
315
+ "tags_all": {
316
+ "Name": "My neptune cluster parameter group"
317
+ }
318
+ },
319
+ "after_unknown": {
320
+ "arn": true,
321
+ "id": true,
322
+ "name_prefix": true,
323
+ "parameter": [
324
+ {}
325
+ ],
326
+ "tags": {},
327
+ "tags_all": {}
328
+ },
329
+ "before_sensitive": false,
330
+ "after_sensitive": {
331
+ "parameter": [
332
+ {}
333
+ ],
334
+ "tags": {},
335
+ "tags_all": {}
336
+ }
337
+ }
338
+ },
339
+ {
340
+ "address": "aws_neptune_subnet_group.example_subnet_group",
341
+ "mode": "managed",
342
+ "type": "aws_neptune_subnet_group",
343
+ "name": "example_subnet_group",
344
+ "provider_name": "registry.terraform.io/hashicorp/aws",
345
+ "change": {
346
+ "actions": [
347
+ "create"
348
+ ],
349
+ "before": null,
350
+ "after": {
351
+ "description": "terraform neptune subnet group",
352
+ "name": "example",
353
+ "tags": {
354
+ "Name": "My neptune subnet group"
355
+ },
356
+ "tags_all": {
357
+ "Name": "My neptune subnet group"
358
+ }
359
+ },
360
+ "after_unknown": {
361
+ "arn": true,
362
+ "id": true,
363
+ "name_prefix": true,
364
+ "subnet_ids": true,
365
+ "tags": {},
366
+ "tags_all": {}
367
+ },
368
+ "before_sensitive": false,
369
+ "after_sensitive": {
370
+ "subnet_ids": [],
371
+ "tags": {},
372
+ "tags_all": {}
373
+ }
374
+ }
375
+ },
376
+ {
377
+ "address": "aws_subnet.subnet1",
378
+ "mode": "managed",
379
+ "type": "aws_subnet",
380
+ "name": "subnet1",
381
+ "provider_name": "registry.terraform.io/hashicorp/aws",
382
+ "change": {
383
+ "actions": [
384
+ "create"
385
+ ],
386
+ "before": null,
387
+ "after": {
388
+ "assign_ipv6_address_on_creation": false,
389
+ "cidr_block": "10.0.1.0/24",
390
+ "customer_owned_ipv4_pool": null,
391
+ "enable_dns64": false,
392
+ "enable_lni_at_device_index": null,
393
+ "enable_resource_name_dns_a_record_on_launch": false,
394
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
395
+ "ipv6_cidr_block": null,
396
+ "ipv6_native": false,
397
+ "map_customer_owned_ip_on_launch": null,
398
+ "map_public_ip_on_launch": false,
399
+ "outpost_arn": null,
400
+ "tags": null,
401
+ "timeouts": null
402
+ },
403
+ "after_unknown": {
404
+ "arn": true,
405
+ "availability_zone": true,
406
+ "availability_zone_id": true,
407
+ "id": true,
408
+ "ipv6_cidr_block_association_id": true,
409
+ "owner_id": true,
410
+ "private_dns_hostname_type_on_launch": true,
411
+ "tags_all": true,
412
+ "vpc_id": true
413
+ },
414
+ "before_sensitive": false,
415
+ "after_sensitive": {
416
+ "tags_all": {}
417
+ }
418
+ }
419
+ },
420
+ {
421
+ "address": "aws_subnet.subnet2",
422
+ "mode": "managed",
423
+ "type": "aws_subnet",
424
+ "name": "subnet2",
425
+ "provider_name": "registry.terraform.io/hashicorp/aws",
426
+ "change": {
427
+ "actions": [
428
+ "create"
429
+ ],
430
+ "before": null,
431
+ "after": {
432
+ "assign_ipv6_address_on_creation": false,
433
+ "cidr_block": "10.0.2.0/24",
434
+ "customer_owned_ipv4_pool": null,
435
+ "enable_dns64": false,
436
+ "enable_lni_at_device_index": null,
437
+ "enable_resource_name_dns_a_record_on_launch": false,
438
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
439
+ "ipv6_cidr_block": null,
440
+ "ipv6_native": false,
441
+ "map_customer_owned_ip_on_launch": null,
442
+ "map_public_ip_on_launch": false,
443
+ "outpost_arn": null,
444
+ "tags": null,
445
+ "timeouts": null
446
+ },
447
+ "after_unknown": {
448
+ "arn": true,
449
+ "availability_zone": true,
450
+ "availability_zone_id": true,
451
+ "id": true,
452
+ "ipv6_cidr_block_association_id": true,
453
+ "owner_id": true,
454
+ "private_dns_hostname_type_on_launch": true,
455
+ "tags_all": true,
456
+ "vpc_id": true
457
+ },
458
+ "before_sensitive": false,
459
+ "after_sensitive": {
460
+ "tags_all": {}
461
+ }
462
+ }
463
+ },
464
+ {
465
+ "address": "aws_vpc.example_vpc",
466
+ "mode": "managed",
467
+ "type": "aws_vpc",
468
+ "name": "example_vpc",
469
+ "provider_name": "registry.terraform.io/hashicorp/aws",
470
+ "change": {
471
+ "actions": [
472
+ "create"
473
+ ],
474
+ "before": null,
475
+ "after": {
476
+ "assign_generated_ipv6_cidr_block": null,
477
+ "cidr_block": "10.0.0.0/16",
478
+ "enable_dns_support": true,
479
+ "instance_tenancy": "default",
480
+ "ipv4_ipam_pool_id": null,
481
+ "ipv4_netmask_length": null,
482
+ "ipv6_ipam_pool_id": null,
483
+ "ipv6_netmask_length": null,
484
+ "tags": null
485
+ },
486
+ "after_unknown": {
487
+ "arn": true,
488
+ "default_network_acl_id": true,
489
+ "default_route_table_id": true,
490
+ "default_security_group_id": true,
491
+ "dhcp_options_id": true,
492
+ "enable_dns_hostnames": true,
493
+ "enable_network_address_usage_metrics": true,
494
+ "id": true,
495
+ "ipv6_association_id": true,
496
+ "ipv6_cidr_block": true,
497
+ "ipv6_cidr_block_network_border_group": true,
498
+ "main_route_table_id": true,
499
+ "owner_id": true,
500
+ "tags_all": true
501
+ },
502
+ "before_sensitive": false,
503
+ "after_sensitive": {
504
+ "tags_all": {}
505
+ }
506
+ }
507
+ }
508
+ ],
509
+ "configuration": {
510
+ "provider_config": {
511
+ "aws": {
512
+ "name": "aws",
513
+ "full_name": "registry.terraform.io/hashicorp/aws"
514
+ }
515
+ },
516
+ "root_module": {
517
+ "resources": [
518
+ {
519
+ "address": "aws_neptune_cluster.default",
520
+ "mode": "managed",
521
+ "type": "aws_neptune_cluster",
522
+ "name": "default",
523
+ "provider_config_key": "aws",
524
+ "expressions": {
525
+ "allow_major_version_upgrade": {
526
+ "constant_value": false
527
+ },
528
+ "apply_immediately": {
529
+ "constant_value": true
530
+ },
531
+ "availability_zones": {
532
+ "constant_value": [
533
+ "us-east-1a"
534
+ ]
535
+ },
536
+ "backup_retention_period": {
537
+ "constant_value": 2
538
+ },
539
+ "cluster_identifier": {
540
+ "constant_value": "neptune-cluster-demo"
541
+ },
542
+ "copy_tags_to_snapshot": {
543
+ "constant_value": false
544
+ },
545
+ "deletion_protection": {
546
+ "constant_value": false
547
+ },
548
+ "enable_cloudwatch_logs_exports": {
549
+ "constant_value": [
550
+ "audit",
551
+ "slowquery"
552
+ ]
553
+ },
554
+ "engine": {
555
+ "constant_value": "neptune"
556
+ },
557
+ "engine_version": {
558
+ "constant_value": "1.2.1.0"
559
+ },
560
+ "final_snapshot_identifier": {
561
+ "constant_value": "cluster-final-snapshot"
562
+ },
563
+ "iam_database_authentication_enabled": {
564
+ "constant_value": false
565
+ },
566
+ "neptune_cluster_parameter_group_name": {
567
+ "references": [
568
+ "aws_neptune_cluster_parameter_group.example_cluster_parameter_group.id",
569
+ "aws_neptune_cluster_parameter_group.example_cluster_parameter_group"
570
+ ]
571
+ },
572
+ "neptune_subnet_group_name": {
573
+ "references": [
574
+ "aws_neptune_subnet_group.example_subnet_group.id",
575
+ "aws_neptune_subnet_group.example_subnet_group"
576
+ ]
577
+ },
578
+ "port": {
579
+ "constant_value": 8182
580
+ },
581
+ "preferred_backup_window": {
582
+ "constant_value": "07:00-09:00"
583
+ },
584
+ "skip_final_snapshot": {
585
+ "constant_value": true
586
+ },
587
+ "storage_encrypted": {
588
+ "constant_value": false
589
+ },
590
+ "tags": {
591
+ "constant_value": {
592
+ "test-tag": "insert tag"
593
+ }
594
+ }
595
+ },
596
+ "schema_version": 0
597
+ },
598
+ {
599
+ "address": "aws_neptune_cluster_parameter_group.example_cluster_parameter_group",
600
+ "mode": "managed",
601
+ "type": "aws_neptune_cluster_parameter_group",
602
+ "name": "example_cluster_parameter_group",
603
+ "provider_config_key": "aws",
604
+ "expressions": {
605
+ "description": {
606
+ "constant_value": "terraform neptune cluster parameter group"
607
+ },
608
+ "family": {
609
+ "constant_value": "neptune1.2"
610
+ },
611
+ "name": {
612
+ "constant_value": "example"
613
+ },
614
+ "parameter": [
615
+ {
616
+ "name": {
617
+ "constant_value": "neptune_enable_audit_log"
618
+ },
619
+ "value": {
620
+ "constant_value": 1
621
+ }
622
+ }
623
+ ],
624
+ "tags": {
625
+ "constant_value": {
626
+ "Name": "My neptune cluster parameter group"
627
+ }
628
+ }
629
+ },
630
+ "schema_version": 0
631
+ },
632
+ {
633
+ "address": "aws_neptune_subnet_group.example_subnet_group",
634
+ "mode": "managed",
635
+ "type": "aws_neptune_subnet_group",
636
+ "name": "example_subnet_group",
637
+ "provider_config_key": "aws",
638
+ "expressions": {
639
+ "description": {
640
+ "constant_value": "terraform neptune subnet group"
641
+ },
642
+ "name": {
643
+ "constant_value": "example"
644
+ },
645
+ "subnet_ids": {
646
+ "references": [
647
+ "aws_subnet.subnet1.id",
648
+ "aws_subnet.subnet1",
649
+ "aws_subnet.subnet2.id",
650
+ "aws_subnet.subnet2"
651
+ ]
652
+ },
653
+ "tags": {
654
+ "constant_value": {
655
+ "Name": "My neptune subnet group"
656
+ }
657
+ }
658
+ },
659
+ "schema_version": 0
660
+ },
661
+ {
662
+ "address": "aws_subnet.subnet1",
663
+ "mode": "managed",
664
+ "type": "aws_subnet",
665
+ "name": "subnet1",
666
+ "provider_config_key": "aws",
667
+ "expressions": {
668
+ "cidr_block": {
669
+ "constant_value": "10.0.1.0/24"
670
+ },
671
+ "vpc_id": {
672
+ "references": [
673
+ "aws_vpc.example_vpc.id",
674
+ "aws_vpc.example_vpc"
675
+ ]
676
+ }
677
+ },
678
+ "schema_version": 1
679
+ },
680
+ {
681
+ "address": "aws_subnet.subnet2",
682
+ "mode": "managed",
683
+ "type": "aws_subnet",
684
+ "name": "subnet2",
685
+ "provider_config_key": "aws",
686
+ "expressions": {
687
+ "cidr_block": {
688
+ "constant_value": "10.0.2.0/24"
689
+ },
690
+ "vpc_id": {
691
+ "references": [
692
+ "aws_vpc.example_vpc.id",
693
+ "aws_vpc.example_vpc"
694
+ ]
695
+ }
696
+ },
697
+ "schema_version": 1
698
+ },
699
+ {
700
+ "address": "aws_vpc.example_vpc",
701
+ "mode": "managed",
702
+ "type": "aws_vpc",
703
+ "name": "example_vpc",
704
+ "provider_config_key": "aws",
705
+ "expressions": {
706
+ "cidr_block": {
707
+ "constant_value": "10.0.0.0/16"
708
+ }
709
+ },
710
+ "schema_version": 1
711
+ }
712
+ ]
713
+ }
714
+ },
715
+ "relevant_attributes": [
716
+ {
717
+ "resource": "aws_subnet.subnet1",
718
+ "attribute": [
719
+ "id"
720
+ ]
721
+ },
722
+ {
723
+ "resource": "aws_subnet.subnet2",
724
+ "attribute": [
725
+ "id"
726
+ ]
727
+ },
728
+ {
729
+ "resource": "aws_neptune_cluster_parameter_group.example_cluster_parameter_group",
730
+ "attribute": [
731
+ "id"
732
+ ]
733
+ },
734
+ {
735
+ "resource": "aws_neptune_subnet_group.example_subnet_group",
736
+ "attribute": [
737
+ "id"
738
+ ]
739
+ },
740
+ {
741
+ "resource": "aws_vpc.example_vpc",
742
+ "attribute": [
743
+ "id"
744
+ ]
745
+ }
746
+ ],
747
+ "timestamp": "2024-01-03T17:28:49Z",
748
+ "errored": false
749
+ }
human_reference_dataset/iac-eval/templates/aws_redshift_cluster/sns-event/main.tf ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ resource "aws_redshift_cluster" "example" {
2
+ cluster_identifier = "tf-redshift-cluster"
3
+ database_name = "mydb"
4
+ master_username = "exampleuser"
5
+ master_password = "Mustbe8characters"
6
+ node_type = "ra3.xlplus"
7
+ cluster_type = "single-node"
8
+ skip_final_snapshot = true
9
+ cluster_parameter_group_name = aws_redshift_parameter_group.bar.id
10
+ }
11
+
12
+ resource "aws_redshift_parameter_group" "bar" {
13
+ name = "parameter-group-test-terraform"
14
+ family = "redshift-1.0"
15
+
16
+ parameter {
17
+ name = "require_ssl"
18
+ value = "true"
19
+ }
20
+
21
+ parameter {
22
+ name = "query_group"
23
+ value = "example"
24
+ }
25
+
26
+ parameter {
27
+ name = "enable_user_activity_logging"
28
+ value = "true"
29
+ }
30
+ }
31
+
32
+ resource "aws_sns_topic" "default" {
33
+ name = "redshift-events"
34
+ }
35
+
36
+ resource "aws_redshift_event_subscription" "default" {
37
+ name = "redshift-event-sub"
38
+ sns_topic_arn = aws_sns_topic.default.arn
39
+
40
+ source_type = "cluster-parameter-group"
41
+ source_ids = [aws_redshift_parameter_group.bar.id]
42
+
43
+ severity = "INFO"
44
+
45
+ event_categories = [
46
+ "configuration",
47
+ "management",
48
+ "monitoring",
49
+ "security",
50
+ ]
51
+
52
+ tags = {
53
+ Name = "default"
54
+ }
55
+ }
human_reference_dataset/iac-eval/templates/aws_redshift_cluster/sns-event/tfplan.json ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.6.6",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_redshift_cluster.example",
9
+ "mode": "managed",
10
+ "type": "aws_redshift_cluster",
11
+ "name": "example",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "allow_version_upgrade": true,
16
+ "apply_immediately": false,
17
+ "automated_snapshot_retention_period": 1,
18
+ "availability_zone_relocation_enabled": null,
19
+ "cluster_identifier": "tf-redshift-cluster",
20
+ "cluster_type": "single-node",
21
+ "cluster_version": "1.0",
22
+ "database_name": "mydb",
23
+ "elastic_ip": null,
24
+ "encrypted": false,
25
+ "final_snapshot_identifier": null,
26
+ "logging": [],
27
+ "maintenance_track_name": "current",
28
+ "manage_master_password": null,
29
+ "manual_snapshot_retention_period": -1,
30
+ "master_password": "Mustbe8characters",
31
+ "master_username": "exampleuser",
32
+ "node_type": "ra3.xlplus",
33
+ "number_of_nodes": 1,
34
+ "owner_account": null,
35
+ "port": 5439,
36
+ "publicly_accessible": true,
37
+ "skip_final_snapshot": true,
38
+ "snapshot_arn": null,
39
+ "snapshot_cluster_identifier": null,
40
+ "snapshot_copy": [],
41
+ "snapshot_identifier": null,
42
+ "tags": null,
43
+ "timeouts": null
44
+ },
45
+ "sensitive_values": {
46
+ "cluster_nodes": [],
47
+ "iam_roles": [],
48
+ "logging": [],
49
+ "snapshot_copy": [],
50
+ "tags_all": {},
51
+ "vpc_security_group_ids": []
52
+ }
53
+ },
54
+ {
55
+ "address": "aws_redshift_event_subscription.default",
56
+ "mode": "managed",
57
+ "type": "aws_redshift_event_subscription",
58
+ "name": "default",
59
+ "provider_name": "registry.terraform.io/hashicorp/aws",
60
+ "schema_version": 0,
61
+ "values": {
62
+ "enabled": true,
63
+ "event_categories": [
64
+ "configuration",
65
+ "management",
66
+ "monitoring",
67
+ "security"
68
+ ],
69
+ "name": "redshift-event-sub",
70
+ "severity": "INFO",
71
+ "source_type": "cluster-parameter-group",
72
+ "tags": {
73
+ "Name": "default"
74
+ },
75
+ "tags_all": {
76
+ "Name": "default"
77
+ },
78
+ "timeouts": null
79
+ },
80
+ "sensitive_values": {
81
+ "event_categories": [
82
+ false,
83
+ false,
84
+ false,
85
+ false
86
+ ],
87
+ "source_ids": [],
88
+ "tags": {},
89
+ "tags_all": {}
90
+ }
91
+ },
92
+ {
93
+ "address": "aws_redshift_parameter_group.bar",
94
+ "mode": "managed",
95
+ "type": "aws_redshift_parameter_group",
96
+ "name": "bar",
97
+ "provider_name": "registry.terraform.io/hashicorp/aws",
98
+ "schema_version": 0,
99
+ "values": {
100
+ "description": "Managed by Terraform",
101
+ "family": "redshift-1.0",
102
+ "name": "parameter-group-test-terraform",
103
+ "parameter": [
104
+ {
105
+ "name": "enable_user_activity_logging",
106
+ "value": "true"
107
+ },
108
+ {
109
+ "name": "query_group",
110
+ "value": "example"
111
+ },
112
+ {
113
+ "name": "require_ssl",
114
+ "value": "true"
115
+ }
116
+ ],
117
+ "tags": null
118
+ },
119
+ "sensitive_values": {
120
+ "parameter": [
121
+ {},
122
+ {},
123
+ {}
124
+ ],
125
+ "tags_all": {}
126
+ }
127
+ },
128
+ {
129
+ "address": "aws_sns_topic.default",
130
+ "mode": "managed",
131
+ "type": "aws_sns_topic",
132
+ "name": "default",
133
+ "provider_name": "registry.terraform.io/hashicorp/aws",
134
+ "schema_version": 0,
135
+ "values": {
136
+ "application_failure_feedback_role_arn": null,
137
+ "application_success_feedback_role_arn": null,
138
+ "application_success_feedback_sample_rate": null,
139
+ "archive_policy": null,
140
+ "content_based_deduplication": false,
141
+ "delivery_policy": null,
142
+ "display_name": null,
143
+ "fifo_topic": false,
144
+ "firehose_failure_feedback_role_arn": null,
145
+ "firehose_success_feedback_role_arn": null,
146
+ "firehose_success_feedback_sample_rate": null,
147
+ "http_failure_feedback_role_arn": null,
148
+ "http_success_feedback_role_arn": null,
149
+ "http_success_feedback_sample_rate": null,
150
+ "kms_master_key_id": null,
151
+ "lambda_failure_feedback_role_arn": null,
152
+ "lambda_success_feedback_role_arn": null,
153
+ "lambda_success_feedback_sample_rate": null,
154
+ "name": "redshift-events",
155
+ "sqs_failure_feedback_role_arn": null,
156
+ "sqs_success_feedback_role_arn": null,
157
+ "sqs_success_feedback_sample_rate": null,
158
+ "tags": null
159
+ },
160
+ "sensitive_values": {
161
+ "tags_all": {}
162
+ }
163
+ }
164
+ ]
165
+ }
166
+ },
167
+ "resource_changes": [
168
+ {
169
+ "address": "aws_redshift_cluster.example",
170
+ "mode": "managed",
171
+ "type": "aws_redshift_cluster",
172
+ "name": "example",
173
+ "provider_name": "registry.terraform.io/hashicorp/aws",
174
+ "change": {
175
+ "actions": [
176
+ "create"
177
+ ],
178
+ "before": null,
179
+ "after": {
180
+ "allow_version_upgrade": true,
181
+ "apply_immediately": false,
182
+ "automated_snapshot_retention_period": 1,
183
+ "availability_zone_relocation_enabled": null,
184
+ "cluster_identifier": "tf-redshift-cluster",
185
+ "cluster_type": "single-node",
186
+ "cluster_version": "1.0",
187
+ "database_name": "mydb",
188
+ "elastic_ip": null,
189
+ "encrypted": false,
190
+ "final_snapshot_identifier": null,
191
+ "logging": [],
192
+ "maintenance_track_name": "current",
193
+ "manage_master_password": null,
194
+ "manual_snapshot_retention_period": -1,
195
+ "master_password": "Mustbe8characters",
196
+ "master_username": "exampleuser",
197
+ "node_type": "ra3.xlplus",
198
+ "number_of_nodes": 1,
199
+ "owner_account": null,
200
+ "port": 5439,
201
+ "publicly_accessible": true,
202
+ "skip_final_snapshot": true,
203
+ "snapshot_arn": null,
204
+ "snapshot_cluster_identifier": null,
205
+ "snapshot_copy": [],
206
+ "snapshot_identifier": null,
207
+ "tags": null,
208
+ "timeouts": null
209
+ },
210
+ "after_unknown": {
211
+ "aqua_configuration_status": true,
212
+ "arn": true,
213
+ "availability_zone": true,
214
+ "cluster_namespace_arn": true,
215
+ "cluster_nodes": true,
216
+ "cluster_parameter_group_name": true,
217
+ "cluster_public_key": true,
218
+ "cluster_revision_number": true,
219
+ "cluster_subnet_group_name": true,
220
+ "default_iam_role_arn": true,
221
+ "dns_name": true,
222
+ "endpoint": true,
223
+ "enhanced_vpc_routing": true,
224
+ "iam_roles": true,
225
+ "id": true,
226
+ "kms_key_id": true,
227
+ "logging": [],
228
+ "master_password_secret_arn": true,
229
+ "master_password_secret_kms_key_id": true,
230
+ "preferred_maintenance_window": true,
231
+ "snapshot_copy": [],
232
+ "tags_all": true,
233
+ "vpc_security_group_ids": true
234
+ },
235
+ "before_sensitive": false,
236
+ "after_sensitive": {
237
+ "cluster_nodes": [],
238
+ "iam_roles": [],
239
+ "logging": [],
240
+ "master_password": true,
241
+ "snapshot_copy": [],
242
+ "tags_all": {},
243
+ "vpc_security_group_ids": []
244
+ }
245
+ }
246
+ },
247
+ {
248
+ "address": "aws_redshift_event_subscription.default",
249
+ "mode": "managed",
250
+ "type": "aws_redshift_event_subscription",
251
+ "name": "default",
252
+ "provider_name": "registry.terraform.io/hashicorp/aws",
253
+ "change": {
254
+ "actions": [
255
+ "create"
256
+ ],
257
+ "before": null,
258
+ "after": {
259
+ "enabled": true,
260
+ "event_categories": [
261
+ "configuration",
262
+ "management",
263
+ "monitoring",
264
+ "security"
265
+ ],
266
+ "name": "redshift-event-sub",
267
+ "severity": "INFO",
268
+ "source_type": "cluster-parameter-group",
269
+ "tags": {
270
+ "Name": "default"
271
+ },
272
+ "tags_all": {
273
+ "Name": "default"
274
+ },
275
+ "timeouts": null
276
+ },
277
+ "after_unknown": {
278
+ "arn": true,
279
+ "customer_aws_id": true,
280
+ "event_categories": [
281
+ false,
282
+ false,
283
+ false,
284
+ false
285
+ ],
286
+ "id": true,
287
+ "sns_topic_arn": true,
288
+ "source_ids": true,
289
+ "status": true,
290
+ "tags": {},
291
+ "tags_all": {}
292
+ },
293
+ "before_sensitive": false,
294
+ "after_sensitive": {
295
+ "event_categories": [
296
+ false,
297
+ false,
298
+ false,
299
+ false
300
+ ],
301
+ "source_ids": [],
302
+ "tags": {},
303
+ "tags_all": {}
304
+ }
305
+ }
306
+ },
307
+ {
308
+ "address": "aws_redshift_parameter_group.bar",
309
+ "mode": "managed",
310
+ "type": "aws_redshift_parameter_group",
311
+ "name": "bar",
312
+ "provider_name": "registry.terraform.io/hashicorp/aws",
313
+ "change": {
314
+ "actions": [
315
+ "create"
316
+ ],
317
+ "before": null,
318
+ "after": {
319
+ "description": "Managed by Terraform",
320
+ "family": "redshift-1.0",
321
+ "name": "parameter-group-test-terraform",
322
+ "parameter": [
323
+ {
324
+ "name": "enable_user_activity_logging",
325
+ "value": "true"
326
+ },
327
+ {
328
+ "name": "query_group",
329
+ "value": "example"
330
+ },
331
+ {
332
+ "name": "require_ssl",
333
+ "value": "true"
334
+ }
335
+ ],
336
+ "tags": null
337
+ },
338
+ "after_unknown": {
339
+ "arn": true,
340
+ "id": true,
341
+ "parameter": [
342
+ {},
343
+ {},
344
+ {}
345
+ ],
346
+ "tags_all": true
347
+ },
348
+ "before_sensitive": false,
349
+ "after_sensitive": {
350
+ "parameter": [
351
+ {},
352
+ {},
353
+ {}
354
+ ],
355
+ "tags_all": {}
356
+ }
357
+ }
358
+ },
359
+ {
360
+ "address": "aws_sns_topic.default",
361
+ "mode": "managed",
362
+ "type": "aws_sns_topic",
363
+ "name": "default",
364
+ "provider_name": "registry.terraform.io/hashicorp/aws",
365
+ "change": {
366
+ "actions": [
367
+ "create"
368
+ ],
369
+ "before": null,
370
+ "after": {
371
+ "application_failure_feedback_role_arn": null,
372
+ "application_success_feedback_role_arn": null,
373
+ "application_success_feedback_sample_rate": null,
374
+ "archive_policy": null,
375
+ "content_based_deduplication": false,
376
+ "delivery_policy": null,
377
+ "display_name": null,
378
+ "fifo_topic": false,
379
+ "firehose_failure_feedback_role_arn": null,
380
+ "firehose_success_feedback_role_arn": null,
381
+ "firehose_success_feedback_sample_rate": null,
382
+ "http_failure_feedback_role_arn": null,
383
+ "http_success_feedback_role_arn": null,
384
+ "http_success_feedback_sample_rate": null,
385
+ "kms_master_key_id": null,
386
+ "lambda_failure_feedback_role_arn": null,
387
+ "lambda_success_feedback_role_arn": null,
388
+ "lambda_success_feedback_sample_rate": null,
389
+ "name": "redshift-events",
390
+ "sqs_failure_feedback_role_arn": null,
391
+ "sqs_success_feedback_role_arn": null,
392
+ "sqs_success_feedback_sample_rate": null,
393
+ "tags": null
394
+ },
395
+ "after_unknown": {
396
+ "arn": true,
397
+ "beginning_archive_time": true,
398
+ "id": true,
399
+ "name_prefix": true,
400
+ "owner": true,
401
+ "policy": true,
402
+ "signature_version": true,
403
+ "tags_all": true,
404
+ "tracing_config": true
405
+ },
406
+ "before_sensitive": false,
407
+ "after_sensitive": {
408
+ "tags_all": {}
409
+ }
410
+ }
411
+ }
412
+ ],
413
+ "configuration": {
414
+ "provider_config": {
415
+ "aws": {
416
+ "name": "aws",
417
+ "full_name": "registry.terraform.io/hashicorp/aws"
418
+ }
419
+ },
420
+ "root_module": {
421
+ "resources": [
422
+ {
423
+ "address": "aws_redshift_cluster.example",
424
+ "mode": "managed",
425
+ "type": "aws_redshift_cluster",
426
+ "name": "example",
427
+ "provider_config_key": "aws",
428
+ "expressions": {
429
+ "cluster_identifier": {
430
+ "constant_value": "tf-redshift-cluster"
431
+ },
432
+ "cluster_parameter_group_name": {
433
+ "references": [
434
+ "aws_redshift_parameter_group.bar.id",
435
+ "aws_redshift_parameter_group.bar"
436
+ ]
437
+ },
438
+ "cluster_type": {
439
+ "constant_value": "single-node"
440
+ },
441
+ "database_name": {
442
+ "constant_value": "mydb"
443
+ },
444
+ "master_password": {
445
+ "constant_value": "Mustbe8characters"
446
+ },
447
+ "master_username": {
448
+ "constant_value": "exampleuser"
449
+ },
450
+ "node_type": {
451
+ "constant_value": "ra3.xlplus"
452
+ },
453
+ "skip_final_snapshot": {
454
+ "constant_value": true
455
+ }
456
+ },
457
+ "schema_version": 0
458
+ },
459
+ {
460
+ "address": "aws_redshift_event_subscription.default",
461
+ "mode": "managed",
462
+ "type": "aws_redshift_event_subscription",
463
+ "name": "default",
464
+ "provider_config_key": "aws",
465
+ "expressions": {
466
+ "event_categories": {
467
+ "constant_value": [
468
+ "configuration",
469
+ "management",
470
+ "monitoring",
471
+ "security"
472
+ ]
473
+ },
474
+ "name": {
475
+ "constant_value": "redshift-event-sub"
476
+ },
477
+ "severity": {
478
+ "constant_value": "INFO"
479
+ },
480
+ "sns_topic_arn": {
481
+ "references": [
482
+ "aws_sns_topic.default.arn",
483
+ "aws_sns_topic.default"
484
+ ]
485
+ },
486
+ "source_ids": {
487
+ "references": [
488
+ "aws_redshift_parameter_group.bar.id",
489
+ "aws_redshift_parameter_group.bar"
490
+ ]
491
+ },
492
+ "source_type": {
493
+ "constant_value": "cluster-parameter-group"
494
+ },
495
+ "tags": {
496
+ "constant_value": {
497
+ "Name": "default"
498
+ }
499
+ }
500
+ },
501
+ "schema_version": 0
502
+ },
503
+ {
504
+ "address": "aws_redshift_parameter_group.bar",
505
+ "mode": "managed",
506
+ "type": "aws_redshift_parameter_group",
507
+ "name": "bar",
508
+ "provider_config_key": "aws",
509
+ "expressions": {
510
+ "family": {
511
+ "constant_value": "redshift-1.0"
512
+ },
513
+ "name": {
514
+ "constant_value": "parameter-group-test-terraform"
515
+ },
516
+ "parameter": [
517
+ {
518
+ "name": {
519
+ "constant_value": "require_ssl"
520
+ },
521
+ "value": {
522
+ "constant_value": "true"
523
+ }
524
+ },
525
+ {
526
+ "name": {
527
+ "constant_value": "query_group"
528
+ },
529
+ "value": {
530
+ "constant_value": "example"
531
+ }
532
+ },
533
+ {
534
+ "name": {
535
+ "constant_value": "enable_user_activity_logging"
536
+ },
537
+ "value": {
538
+ "constant_value": "true"
539
+ }
540
+ }
541
+ ]
542
+ },
543
+ "schema_version": 0
544
+ },
545
+ {
546
+ "address": "aws_sns_topic.default",
547
+ "mode": "managed",
548
+ "type": "aws_sns_topic",
549
+ "name": "default",
550
+ "provider_config_key": "aws",
551
+ "expressions": {
552
+ "name": {
553
+ "constant_value": "redshift-events"
554
+ }
555
+ },
556
+ "schema_version": 0
557
+ }
558
+ ]
559
+ }
560
+ },
561
+ "relevant_attributes": [
562
+ {
563
+ "resource": "aws_redshift_parameter_group.bar",
564
+ "attribute": [
565
+ "id"
566
+ ]
567
+ },
568
+ {
569
+ "resource": "aws_sns_topic.default",
570
+ "attribute": [
571
+ "arn"
572
+ ]
573
+ }
574
+ ],
575
+ "timestamp": "2024-01-04T04:48:23Z",
576
+ "errored": false
577
+ }
human_reference_dataset/iac-eval/templates/aws_redshift_cluster/subnet-group/main.tf ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ resource "aws_redshift_cluster" "example" {
2
+ cluster_identifier = "tf-redshift-cluster"
3
+ database_name = "mydb"
4
+ master_username = "exampleuser"
5
+ master_password = "Mustbe8characters"
6
+ node_type = "ra3.xlplus"
7
+ cluster_type = "single-node"
8
+ skip_final_snapshot = true
9
+ }
10
+
11
+ resource "aws_redshift_endpoint_access" "example" {
12
+ endpoint_name = "example"
13
+ subnet_group_name = aws_redshift_subnet_group.foobar.id
14
+ cluster_identifier = aws_redshift_cluster.example.cluster_identifier
15
+ }
16
+
17
+ resource "aws_vpc" "foo" {
18
+ cidr_block = "10.1.0.0/16"
19
+ }
20
+
21
+ resource "aws_subnet" "foo" {
22
+ cidr_block = "10.1.1.0/24"
23
+ availability_zone = "us-east-1a"
24
+ vpc_id = aws_vpc.foo.id
25
+
26
+ tags = {
27
+ Name = "tf-dbsubnet-test-1"
28
+ }
29
+ }
30
+
31
+ resource "aws_subnet" "bar" {
32
+ cidr_block = "10.1.2.0/24"
33
+ availability_zone = "us-east-1b"
34
+ vpc_id = aws_vpc.foo.id
35
+
36
+ tags = {
37
+ Name = "tf-dbsubnet-test-2"
38
+ }
39
+ }
40
+
41
+ resource "aws_redshift_subnet_group" "foobar" {
42
+ name = "foo"
43
+ subnet_ids = [aws_subnet.foo.id, aws_subnet.bar.id]
44
+
45
+ tags = {
46
+ environment = "Production"
47
+ }
48
+ }
human_reference_dataset/iac-eval/templates/aws_redshift_cluster/subnet-group/tfplan.json ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.6.6",
4
+ "planned_values": {
5
+ "root_module": {
6
+ "resources": [
7
+ {
8
+ "address": "aws_redshift_cluster.example",
9
+ "mode": "managed",
10
+ "type": "aws_redshift_cluster",
11
+ "name": "example",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "schema_version": 0,
14
+ "values": {
15
+ "allow_version_upgrade": true,
16
+ "apply_immediately": false,
17
+ "automated_snapshot_retention_period": 1,
18
+ "availability_zone_relocation_enabled": null,
19
+ "cluster_identifier": "tf-redshift-cluster",
20
+ "cluster_type": "single-node",
21
+ "cluster_version": "1.0",
22
+ "database_name": "mydb",
23
+ "elastic_ip": null,
24
+ "encrypted": false,
25
+ "final_snapshot_identifier": null,
26
+ "logging": [],
27
+ "maintenance_track_name": "current",
28
+ "manage_master_password": null,
29
+ "manual_snapshot_retention_period": -1,
30
+ "master_password": "Mustbe8characters",
31
+ "master_username": "exampleuser",
32
+ "node_type": "ra3.xlplus",
33
+ "number_of_nodes": 1,
34
+ "owner_account": null,
35
+ "port": 5439,
36
+ "publicly_accessible": true,
37
+ "skip_final_snapshot": true,
38
+ "snapshot_arn": null,
39
+ "snapshot_cluster_identifier": null,
40
+ "snapshot_copy": [],
41
+ "snapshot_identifier": null,
42
+ "tags": null,
43
+ "timeouts": null
44
+ },
45
+ "sensitive_values": {
46
+ "cluster_nodes": [],
47
+ "iam_roles": [],
48
+ "logging": [],
49
+ "snapshot_copy": [],
50
+ "tags_all": {},
51
+ "vpc_security_group_ids": []
52
+ }
53
+ },
54
+ {
55
+ "address": "aws_redshift_endpoint_access.example",
56
+ "mode": "managed",
57
+ "type": "aws_redshift_endpoint_access",
58
+ "name": "example",
59
+ "provider_name": "registry.terraform.io/hashicorp/aws",
60
+ "schema_version": 0,
61
+ "values": {
62
+ "cluster_identifier": "tf-redshift-cluster",
63
+ "endpoint_name": "example"
64
+ },
65
+ "sensitive_values": {
66
+ "vpc_endpoint": [],
67
+ "vpc_security_group_ids": []
68
+ }
69
+ },
70
+ {
71
+ "address": "aws_redshift_subnet_group.foobar",
72
+ "mode": "managed",
73
+ "type": "aws_redshift_subnet_group",
74
+ "name": "foobar",
75
+ "provider_name": "registry.terraform.io/hashicorp/aws",
76
+ "schema_version": 0,
77
+ "values": {
78
+ "description": "Managed by Terraform",
79
+ "name": "foo",
80
+ "tags": {
81
+ "environment": "Production"
82
+ },
83
+ "tags_all": {
84
+ "environment": "Production"
85
+ }
86
+ },
87
+ "sensitive_values": {
88
+ "subnet_ids": [],
89
+ "tags": {},
90
+ "tags_all": {}
91
+ }
92
+ },
93
+ {
94
+ "address": "aws_subnet.bar",
95
+ "mode": "managed",
96
+ "type": "aws_subnet",
97
+ "name": "bar",
98
+ "provider_name": "registry.terraform.io/hashicorp/aws",
99
+ "schema_version": 1,
100
+ "values": {
101
+ "assign_ipv6_address_on_creation": false,
102
+ "availability_zone": "us-east-1b",
103
+ "cidr_block": "10.1.2.0/24",
104
+ "customer_owned_ipv4_pool": null,
105
+ "enable_dns64": false,
106
+ "enable_lni_at_device_index": null,
107
+ "enable_resource_name_dns_a_record_on_launch": false,
108
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
109
+ "ipv6_cidr_block": null,
110
+ "ipv6_native": false,
111
+ "map_customer_owned_ip_on_launch": null,
112
+ "map_public_ip_on_launch": false,
113
+ "outpost_arn": null,
114
+ "tags": {
115
+ "Name": "tf-dbsubnet-test-2"
116
+ },
117
+ "tags_all": {
118
+ "Name": "tf-dbsubnet-test-2"
119
+ },
120
+ "timeouts": null
121
+ },
122
+ "sensitive_values": {
123
+ "tags": {},
124
+ "tags_all": {}
125
+ }
126
+ },
127
+ {
128
+ "address": "aws_subnet.foo",
129
+ "mode": "managed",
130
+ "type": "aws_subnet",
131
+ "name": "foo",
132
+ "provider_name": "registry.terraform.io/hashicorp/aws",
133
+ "schema_version": 1,
134
+ "values": {
135
+ "assign_ipv6_address_on_creation": false,
136
+ "availability_zone": "us-east-1a",
137
+ "cidr_block": "10.1.1.0/24",
138
+ "customer_owned_ipv4_pool": null,
139
+ "enable_dns64": false,
140
+ "enable_lni_at_device_index": null,
141
+ "enable_resource_name_dns_a_record_on_launch": false,
142
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
143
+ "ipv6_cidr_block": null,
144
+ "ipv6_native": false,
145
+ "map_customer_owned_ip_on_launch": null,
146
+ "map_public_ip_on_launch": false,
147
+ "outpost_arn": null,
148
+ "tags": {
149
+ "Name": "tf-dbsubnet-test-1"
150
+ },
151
+ "tags_all": {
152
+ "Name": "tf-dbsubnet-test-1"
153
+ },
154
+ "timeouts": null
155
+ },
156
+ "sensitive_values": {
157
+ "tags": {},
158
+ "tags_all": {}
159
+ }
160
+ },
161
+ {
162
+ "address": "aws_vpc.foo",
163
+ "mode": "managed",
164
+ "type": "aws_vpc",
165
+ "name": "foo",
166
+ "provider_name": "registry.terraform.io/hashicorp/aws",
167
+ "schema_version": 1,
168
+ "values": {
169
+ "assign_generated_ipv6_cidr_block": null,
170
+ "cidr_block": "10.1.0.0/16",
171
+ "enable_dns_support": true,
172
+ "instance_tenancy": "default",
173
+ "ipv4_ipam_pool_id": null,
174
+ "ipv4_netmask_length": null,
175
+ "ipv6_ipam_pool_id": null,
176
+ "ipv6_netmask_length": null,
177
+ "tags": null
178
+ },
179
+ "sensitive_values": {
180
+ "tags_all": {}
181
+ }
182
+ }
183
+ ]
184
+ }
185
+ },
186
+ "resource_changes": [
187
+ {
188
+ "address": "aws_redshift_cluster.example",
189
+ "mode": "managed",
190
+ "type": "aws_redshift_cluster",
191
+ "name": "example",
192
+ "provider_name": "registry.terraform.io/hashicorp/aws",
193
+ "change": {
194
+ "actions": [
195
+ "create"
196
+ ],
197
+ "before": null,
198
+ "after": {
199
+ "allow_version_upgrade": true,
200
+ "apply_immediately": false,
201
+ "automated_snapshot_retention_period": 1,
202
+ "availability_zone_relocation_enabled": null,
203
+ "cluster_identifier": "tf-redshift-cluster",
204
+ "cluster_type": "single-node",
205
+ "cluster_version": "1.0",
206
+ "database_name": "mydb",
207
+ "elastic_ip": null,
208
+ "encrypted": false,
209
+ "final_snapshot_identifier": null,
210
+ "logging": [],
211
+ "maintenance_track_name": "current",
212
+ "manage_master_password": null,
213
+ "manual_snapshot_retention_period": -1,
214
+ "master_password": "Mustbe8characters",
215
+ "master_username": "exampleuser",
216
+ "node_type": "ra3.xlplus",
217
+ "number_of_nodes": 1,
218
+ "owner_account": null,
219
+ "port": 5439,
220
+ "publicly_accessible": true,
221
+ "skip_final_snapshot": true,
222
+ "snapshot_arn": null,
223
+ "snapshot_cluster_identifier": null,
224
+ "snapshot_copy": [],
225
+ "snapshot_identifier": null,
226
+ "tags": null,
227
+ "timeouts": null
228
+ },
229
+ "after_unknown": {
230
+ "aqua_configuration_status": true,
231
+ "arn": true,
232
+ "availability_zone": true,
233
+ "cluster_namespace_arn": true,
234
+ "cluster_nodes": true,
235
+ "cluster_parameter_group_name": true,
236
+ "cluster_public_key": true,
237
+ "cluster_revision_number": true,
238
+ "cluster_subnet_group_name": true,
239
+ "default_iam_role_arn": true,
240
+ "dns_name": true,
241
+ "endpoint": true,
242
+ "enhanced_vpc_routing": true,
243
+ "iam_roles": true,
244
+ "id": true,
245
+ "kms_key_id": true,
246
+ "logging": [],
247
+ "master_password_secret_arn": true,
248
+ "master_password_secret_kms_key_id": true,
249
+ "preferred_maintenance_window": true,
250
+ "snapshot_copy": [],
251
+ "tags_all": true,
252
+ "vpc_security_group_ids": true
253
+ },
254
+ "before_sensitive": false,
255
+ "after_sensitive": {
256
+ "cluster_nodes": [],
257
+ "iam_roles": [],
258
+ "logging": [],
259
+ "master_password": true,
260
+ "snapshot_copy": [],
261
+ "tags_all": {},
262
+ "vpc_security_group_ids": []
263
+ }
264
+ }
265
+ },
266
+ {
267
+ "address": "aws_redshift_endpoint_access.example",
268
+ "mode": "managed",
269
+ "type": "aws_redshift_endpoint_access",
270
+ "name": "example",
271
+ "provider_name": "registry.terraform.io/hashicorp/aws",
272
+ "change": {
273
+ "actions": [
274
+ "create"
275
+ ],
276
+ "before": null,
277
+ "after": {
278
+ "cluster_identifier": "tf-redshift-cluster",
279
+ "endpoint_name": "example"
280
+ },
281
+ "after_unknown": {
282
+ "address": true,
283
+ "id": true,
284
+ "port": true,
285
+ "resource_owner": true,
286
+ "subnet_group_name": true,
287
+ "vpc_endpoint": true,
288
+ "vpc_security_group_ids": true
289
+ },
290
+ "before_sensitive": false,
291
+ "after_sensitive": {
292
+ "vpc_endpoint": [],
293
+ "vpc_security_group_ids": []
294
+ }
295
+ }
296
+ },
297
+ {
298
+ "address": "aws_redshift_subnet_group.foobar",
299
+ "mode": "managed",
300
+ "type": "aws_redshift_subnet_group",
301
+ "name": "foobar",
302
+ "provider_name": "registry.terraform.io/hashicorp/aws",
303
+ "change": {
304
+ "actions": [
305
+ "create"
306
+ ],
307
+ "before": null,
308
+ "after": {
309
+ "description": "Managed by Terraform",
310
+ "name": "foo",
311
+ "tags": {
312
+ "environment": "Production"
313
+ },
314
+ "tags_all": {
315
+ "environment": "Production"
316
+ }
317
+ },
318
+ "after_unknown": {
319
+ "arn": true,
320
+ "id": true,
321
+ "subnet_ids": true,
322
+ "tags": {},
323
+ "tags_all": {}
324
+ },
325
+ "before_sensitive": false,
326
+ "after_sensitive": {
327
+ "subnet_ids": [],
328
+ "tags": {},
329
+ "tags_all": {}
330
+ }
331
+ }
332
+ },
333
+ {
334
+ "address": "aws_subnet.bar",
335
+ "mode": "managed",
336
+ "type": "aws_subnet",
337
+ "name": "bar",
338
+ "provider_name": "registry.terraform.io/hashicorp/aws",
339
+ "change": {
340
+ "actions": [
341
+ "create"
342
+ ],
343
+ "before": null,
344
+ "after": {
345
+ "assign_ipv6_address_on_creation": false,
346
+ "availability_zone": "us-east-1b",
347
+ "cidr_block": "10.1.2.0/24",
348
+ "customer_owned_ipv4_pool": null,
349
+ "enable_dns64": false,
350
+ "enable_lni_at_device_index": null,
351
+ "enable_resource_name_dns_a_record_on_launch": false,
352
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
353
+ "ipv6_cidr_block": null,
354
+ "ipv6_native": false,
355
+ "map_customer_owned_ip_on_launch": null,
356
+ "map_public_ip_on_launch": false,
357
+ "outpost_arn": null,
358
+ "tags": {
359
+ "Name": "tf-dbsubnet-test-2"
360
+ },
361
+ "tags_all": {
362
+ "Name": "tf-dbsubnet-test-2"
363
+ },
364
+ "timeouts": null
365
+ },
366
+ "after_unknown": {
367
+ "arn": true,
368
+ "availability_zone_id": true,
369
+ "id": true,
370
+ "ipv6_cidr_block_association_id": true,
371
+ "owner_id": true,
372
+ "private_dns_hostname_type_on_launch": true,
373
+ "tags": {},
374
+ "tags_all": {},
375
+ "vpc_id": true
376
+ },
377
+ "before_sensitive": false,
378
+ "after_sensitive": {
379
+ "tags": {},
380
+ "tags_all": {}
381
+ }
382
+ }
383
+ },
384
+ {
385
+ "address": "aws_subnet.foo",
386
+ "mode": "managed",
387
+ "type": "aws_subnet",
388
+ "name": "foo",
389
+ "provider_name": "registry.terraform.io/hashicorp/aws",
390
+ "change": {
391
+ "actions": [
392
+ "create"
393
+ ],
394
+ "before": null,
395
+ "after": {
396
+ "assign_ipv6_address_on_creation": false,
397
+ "availability_zone": "us-east-1a",
398
+ "cidr_block": "10.1.1.0/24",
399
+ "customer_owned_ipv4_pool": null,
400
+ "enable_dns64": false,
401
+ "enable_lni_at_device_index": null,
402
+ "enable_resource_name_dns_a_record_on_launch": false,
403
+ "enable_resource_name_dns_aaaa_record_on_launch": false,
404
+ "ipv6_cidr_block": null,
405
+ "ipv6_native": false,
406
+ "map_customer_owned_ip_on_launch": null,
407
+ "map_public_ip_on_launch": false,
408
+ "outpost_arn": null,
409
+ "tags": {
410
+ "Name": "tf-dbsubnet-test-1"
411
+ },
412
+ "tags_all": {
413
+ "Name": "tf-dbsubnet-test-1"
414
+ },
415
+ "timeouts": null
416
+ },
417
+ "after_unknown": {
418
+ "arn": true,
419
+ "availability_zone_id": true,
420
+ "id": true,
421
+ "ipv6_cidr_block_association_id": true,
422
+ "owner_id": true,
423
+ "private_dns_hostname_type_on_launch": true,
424
+ "tags": {},
425
+ "tags_all": {},
426
+ "vpc_id": true
427
+ },
428
+ "before_sensitive": false,
429
+ "after_sensitive": {
430
+ "tags": {},
431
+ "tags_all": {}
432
+ }
433
+ }
434
+ },
435
+ {
436
+ "address": "aws_vpc.foo",
437
+ "mode": "managed",
438
+ "type": "aws_vpc",
439
+ "name": "foo",
440
+ "provider_name": "registry.terraform.io/hashicorp/aws",
441
+ "change": {
442
+ "actions": [
443
+ "create"
444
+ ],
445
+ "before": null,
446
+ "after": {
447
+ "assign_generated_ipv6_cidr_block": null,
448
+ "cidr_block": "10.1.0.0/16",
449
+ "enable_dns_support": true,
450
+ "instance_tenancy": "default",
451
+ "ipv4_ipam_pool_id": null,
452
+ "ipv4_netmask_length": null,
453
+ "ipv6_ipam_pool_id": null,
454
+ "ipv6_netmask_length": null,
455
+ "tags": null
456
+ },
457
+ "after_unknown": {
458
+ "arn": true,
459
+ "default_network_acl_id": true,
460
+ "default_route_table_id": true,
461
+ "default_security_group_id": true,
462
+ "dhcp_options_id": true,
463
+ "enable_dns_hostnames": true,
464
+ "enable_network_address_usage_metrics": true,
465
+ "id": true,
466
+ "ipv6_association_id": true,
467
+ "ipv6_cidr_block": true,
468
+ "ipv6_cidr_block_network_border_group": true,
469
+ "main_route_table_id": true,
470
+ "owner_id": true,
471
+ "tags_all": true
472
+ },
473
+ "before_sensitive": false,
474
+ "after_sensitive": {
475
+ "tags_all": {}
476
+ }
477
+ }
478
+ }
479
+ ],
480
+ "configuration": {
481
+ "provider_config": {
482
+ "aws": {
483
+ "name": "aws",
484
+ "full_name": "registry.terraform.io/hashicorp/aws"
485
+ }
486
+ },
487
+ "root_module": {
488
+ "resources": [
489
+ {
490
+ "address": "aws_redshift_cluster.example",
491
+ "mode": "managed",
492
+ "type": "aws_redshift_cluster",
493
+ "name": "example",
494
+ "provider_config_key": "aws",
495
+ "expressions": {
496
+ "cluster_identifier": {
497
+ "constant_value": "tf-redshift-cluster"
498
+ },
499
+ "cluster_type": {
500
+ "constant_value": "single-node"
501
+ },
502
+ "database_name": {
503
+ "constant_value": "mydb"
504
+ },
505
+ "master_password": {
506
+ "constant_value": "Mustbe8characters"
507
+ },
508
+ "master_username": {
509
+ "constant_value": "exampleuser"
510
+ },
511
+ "node_type": {
512
+ "constant_value": "ra3.xlplus"
513
+ },
514
+ "skip_final_snapshot": {
515
+ "constant_value": true
516
+ }
517
+ },
518
+ "schema_version": 0
519
+ },
520
+ {
521
+ "address": "aws_redshift_endpoint_access.example",
522
+ "mode": "managed",
523
+ "type": "aws_redshift_endpoint_access",
524
+ "name": "example",
525
+ "provider_config_key": "aws",
526
+ "expressions": {
527
+ "cluster_identifier": {
528
+ "references": [
529
+ "aws_redshift_cluster.example.cluster_identifier",
530
+ "aws_redshift_cluster.example"
531
+ ]
532
+ },
533
+ "endpoint_name": {
534
+ "constant_value": "example"
535
+ },
536
+ "subnet_group_name": {
537
+ "references": [
538
+ "aws_redshift_subnet_group.foobar.id",
539
+ "aws_redshift_subnet_group.foobar"
540
+ ]
541
+ }
542
+ },
543
+ "schema_version": 0
544
+ },
545
+ {
546
+ "address": "aws_redshift_subnet_group.foobar",
547
+ "mode": "managed",
548
+ "type": "aws_redshift_subnet_group",
549
+ "name": "foobar",
550
+ "provider_config_key": "aws",
551
+ "expressions": {
552
+ "name": {
553
+ "constant_value": "foo"
554
+ },
555
+ "subnet_ids": {
556
+ "references": [
557
+ "aws_subnet.foo.id",
558
+ "aws_subnet.foo",
559
+ "aws_subnet.bar.id",
560
+ "aws_subnet.bar"
561
+ ]
562
+ },
563
+ "tags": {
564
+ "constant_value": {
565
+ "environment": "Production"
566
+ }
567
+ }
568
+ },
569
+ "schema_version": 0
570
+ },
571
+ {
572
+ "address": "aws_subnet.bar",
573
+ "mode": "managed",
574
+ "type": "aws_subnet",
575
+ "name": "bar",
576
+ "provider_config_key": "aws",
577
+ "expressions": {
578
+ "availability_zone": {
579
+ "constant_value": "us-east-1b"
580
+ },
581
+ "cidr_block": {
582
+ "constant_value": "10.1.2.0/24"
583
+ },
584
+ "tags": {
585
+ "constant_value": {
586
+ "Name": "tf-dbsubnet-test-2"
587
+ }
588
+ },
589
+ "vpc_id": {
590
+ "references": [
591
+ "aws_vpc.foo.id",
592
+ "aws_vpc.foo"
593
+ ]
594
+ }
595
+ },
596
+ "schema_version": 1
597
+ },
598
+ {
599
+ "address": "aws_subnet.foo",
600
+ "mode": "managed",
601
+ "type": "aws_subnet",
602
+ "name": "foo",
603
+ "provider_config_key": "aws",
604
+ "expressions": {
605
+ "availability_zone": {
606
+ "constant_value": "us-east-1a"
607
+ },
608
+ "cidr_block": {
609
+ "constant_value": "10.1.1.0/24"
610
+ },
611
+ "tags": {
612
+ "constant_value": {
613
+ "Name": "tf-dbsubnet-test-1"
614
+ }
615
+ },
616
+ "vpc_id": {
617
+ "references": [
618
+ "aws_vpc.foo.id",
619
+ "aws_vpc.foo"
620
+ ]
621
+ }
622
+ },
623
+ "schema_version": 1
624
+ },
625
+ {
626
+ "address": "aws_vpc.foo",
627
+ "mode": "managed",
628
+ "type": "aws_vpc",
629
+ "name": "foo",
630
+ "provider_config_key": "aws",
631
+ "expressions": {
632
+ "cidr_block": {
633
+ "constant_value": "10.1.0.0/16"
634
+ }
635
+ },
636
+ "schema_version": 1
637
+ }
638
+ ]
639
+ }
640
+ },
641
+ "relevant_attributes": [
642
+ {
643
+ "resource": "aws_vpc.foo",
644
+ "attribute": [
645
+ "id"
646
+ ]
647
+ },
648
+ {
649
+ "resource": "aws_subnet.foo",
650
+ "attribute": [
651
+ "id"
652
+ ]
653
+ },
654
+ {
655
+ "resource": "aws_subnet.bar",
656
+ "attribute": [
657
+ "id"
658
+ ]
659
+ },
660
+ {
661
+ "resource": "aws_redshift_subnet_group.foobar",
662
+ "attribute": [
663
+ "id"
664
+ ]
665
+ },
666
+ {
667
+ "resource": "aws_redshift_cluster.example",
668
+ "attribute": [
669
+ "cluster_identifier"
670
+ ]
671
+ }
672
+ ],
673
+ "timestamp": "2024-01-04T04:13:46Z",
674
+ "errored": false
675
+ }