Skip to content
This repository has been archived by the owner on Jan 12, 2024. It is now read-only.

C# code generation is not thread-safe #1393

Open
anpaz opened this issue Mar 24, 2022 · 0 comments
Open

C# code generation is not thread-safe #1393

anpaz opened this issue Mar 24, 2022 · 0 comments
Labels
area: code gen (C#) C# code generation bug Something isn't working

Comments

@anpaz
Copy link
Member

anpaz commented Mar 24, 2022

Describe the bug

Recently, we tried to make a performance optimization on iqsharp to call the codegen asynchronously as we might have multiple block of files (one per snippet) that needs to be compiled. The code can be seen here. In essence:

                foreach (var file in allSources)
                {
                    trees.Add(Task.Run(() =>
                    {
                        var codegenContext = string.IsNullOrEmpty(executionTarget)
                            ? CodegenContext.Create(qsCompilation.Namespaces)
                            : CodegenContext.Create(qsCompilation.Namespaces, new Dictionary<string, string>() { { AssemblyConstants.ExecutionTarget, executionTarget } });
                        var code = SimulationCode.generate(file, codegenContext);
                        return CSharpSyntaxTree.ParseText(code, encoding: UTF8Encoding.UTF8);
                    }));
                }

Unfortunately, we started getting random compilation errors as internal variable names like __arg1__ got reused. The problem is that the code in SimulationCode.fs is not thread-safe. In particular there is a count static variable (line 247 that gets reset when a new Specialization is started (line 1015)[https://github.com/microsoft/qsharp-compiler/blob/main/src/QsCompiler/CSharpGeneration/SimulationCode.fs#L1015]

Expected behavior

That calling SimulationCode.generate is thread-safe.

I believe count is actually the only static variable so we should put that into the context and make sure everything is thread-safe. Most of the work is probably going to be in writing some unittests to gate this behavior.

@anpaz anpaz added bug Something isn't working needs triage An initial review by a maintainer is needed labels Mar 24, 2022
@bamarsha bamarsha added area: code gen (C#) C# code generation and removed needs triage An initial review by a maintainer is needed labels Mar 25, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area: code gen (C#) C# code generation bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants