• Stars
    star
    266
  • Rank 154,103 (Top 4 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sjsonnet

A JVM implementation of the Jsonnet configuration language.

Usage

Sjsonnet can be used from Java:

<dependency>
    <groupId>com.databricks</groupId>
    <artifactId>sjsonnet_2.13</artifactId>
    <version>0.4.2</version>
</dependency>
sjsonnet.SjsonnetMain.main0(
    new String[]{"foo.jsonnet"},
    new DefaultParseCache,
    System.in,
    System.out,
    System.err,
    os.package$.MODULE$.pwd(),
    scala.None$.empty()
);

From Scala:

"com.databricks" %% "sjsonnet" % "0.4.2" // SBT
ivy"com.databricks::sjsonnet:0.4.2" // Mill
sjsonnet.SjsonnetMain.main0(
    Array("foo.jsonnet"),
    new DefaultParseCache,
    System.in,
    System.out,
    System.err,
    os.pwd, // working directory
    None
);

As a standalone executable assembly:

$ curl -L https://github.com/databricks/sjsonnet/releases/download/0.4.2/sjsonnet.jar > sjsonnet.jar

$ chmod +x sjsonnet.jar

$ ./sjsonnet.jar
error: Need to pass in a jsonnet file to evaluate
usage: sjsonnet [sjsonnet-options] script-file

  -i, --interactive  Run Mill in interactive mode, suitable for opening REPLs and taking user input
  -n, --indent       How much to indent your output JSON
  -J, --jpath        Specify an additional library search dir (right-most wins)
  -o, --output-file  Write to the output file rather than stdout
  ...

$ ./sjsonnet.jar foo.jsonnet

Or from Javascript:

$ curl -L https://github.com/databricks/sjsonnet/releases/download/0.4.2/sjsonnet.js > sjsonnet.js

$ node

> require("./sjsonnet.js")

> SjsonnetMain.interpret("local f = function(x) x * x; f(11)", {}, {}, "", (wd, imported) => null)
121

> SjsonnetMain.interpret(
    "local f = import 'foo'; f + 'bar'", // code
    {}, // extVars
    {}, // tlaVars
    "", // initial working directory

    // import callback: receives a base directory and the imported path string,
    // returns a tuple of the resolved file path and file contents or file contents resolve method
    (wd, imported) => [wd + "/" + imported, "local bar = 123; bar + bar"],
    // loader callback: receives the tuple from the import callback and returns the file contents
    ([path, content]) => content
    )
'246bar'

Note that since Javascript does not necessarily have access to the filesystem, you have to provide an explicit import callback that you can use to resolve imports yourself (whether through Node's fs module, or by emulating a filesystem in-memory)

Running deeply recursive Jsonnet programs

The depth of recursion is limited by JVM stack size. You can run Sjsonnet with increased stack size as follows:

java -Xss100m -cp sjsonnet.jar sjsonnet.SjsonnetMain foo.jsonnet

The -Xss option above is responsible for JVM stack size. Please try this if you ever run into sjsonnet.Error: Internal Error ... Caused by: java.lang.StackOverflowError ....

There is no analog of --max-stack/-s option of google/jsonnet. The only stack size limit is the one of the JVM.

Architecture

Sjsonnet is implementated as an optimizing interpreter. There are roughly 4 phases:

  • sjsonnet.Parser: parses an input String into a sjsonnet.Expr, which is a Syntax Tree representing the Jsonnet document syntax, using the Fastparse parsing library

  • sjsonnet.StaticOptimizer is a single AST transform that performs static checking, essential rewriting (e.g. assigning indices in the symbol table for variables) and optimizations. The result is another sjsonnet.Expr per input file that can be stored in the parse cache and reused.

  • sjsonnet.Evaluator: recurses over the sjsonnet.Expr produced by the optimizer and converts it into a sjsonnet.Val, a data structure representing the Jsonnet runtime values (basically lazy JSON which can contain function values).

  • sjsonnet.Materializer: recurses over the sjsonnet.Val and converts it into an output ujson.Expr: a non-lazy JSON structure without any remaining un-evaluated function values. This can be serialized to a string formatted in a variety of ways

These three phases are encapsulated in the sjsonnet.Interpreter object.

Some notes on the values used in parts of the pipeline:

  • sjsonnet.Expr: this represents {...} object literal nodes, a + b binary operation nodes, function(a) {...} definitions and f(a) invocations, etc.. Also keeps track of source-offset information so failures can be correlated with line numbers.

  • sjsonnet.Val: essentially the JSON structure (objects, arrays, primitives) but with two modifications. The first is that functions like function(a){...} can still be present in the structure: in Jsonnet you can pass around functions as values and call then later on. The second is that object values & array entries are lazy: e.g. [error 123, 456][1] does not raise an error because the first (erroneous) entry of the array is un-used and thus not evaluated.

  • Classes representing literals extend sjsonnet.Val.Literal which in turn extends both, Expr and Val. This allows the evaluator to skip over them instead of having to convert them from one representation to the other.

Performance

Due to pervasive caching, sjsonnet is much faster than google/jsonnet. See this blog post for more details:

Here's the latest set of benchmarks I've run (as of 18 May 2023) comparing Sjsonnet against google/go-jsonnet and google/jsonnet, measuring the time taken to evaluate an arbitrary config file in the Databricks codebase:

Sjsonnet 0.4.3 google/go-jsonnet 0.20.0 google/jsonnet 0.20.0
staging/runbot-app.jsonnet (~6.6mb output JSON) ~0.10s ~6.5s ~67s

Sjsonnet was run as a long-lived daemon to keep the JVM warm, while go-jsonnet and google/jsonnet were run as subprocesses, following typical usage patterns. The Sjsonnet command line which is run by all of these is defined in MainBenchmark.mainArgs. You need to change it to point to a suitable input before running a benchmark or the profiler.

Benchmark example:

sbt bench/jmh:run -jvmArgs "-XX:+UseStringDeduplication" sjsonnet.MainBenchmark

Profiler:

sbt bench/run

Laziness

The Jsonnet language is lazy: expressions don't get evaluated unless their value is needed, and thus even erroneous expressions do not cause a failure if un-used. This is represented in the Sjsonnet codebase by sjsonnet.Lazy: a wrapper type that encapsulates an arbitrary computation that returns a sjsonnet.Val.

sjsonnet.Lazy is used in several places, representing where laziness is present in the language:

  • Inside sjsonnet.Scope, representing local variable name bindings

  • Inside sjsonnet.Val.Arr, representing the contents of array cells

  • Inside sjsonnet.Val.Obj, representing the contents of object values

Val extends Lazy so that an already computed value can be treated as lazy without having to wrap it.

Unlike google/jsonnet, Sjsonnet caches the results of lazy computations the first time they are evaluated, avoiding wasteful re-computation when a value is used more than once.

Standard Library

Different from google/jsonnet, Sjsonnet does not implement the Jsonnet standard library std in Jsonnet code. Rather, those functions are implemented as intrinsics directly in the host language (in Std.scala). This allows both better error messages when the input types are wrong, as well as better performance for the more computationally-intense builtin functions.

Client-Server

Sjsonnet comes with a built in thin-client and background server, to help mitigate the unfortunate JVM warmup overhead that adds ~1s to every invocation down to 0.2-0.3s. For the simple non-client-server executable, you can use

./mill show sjsonnet[2.13.0].assembly

To create the executable. For the client-server executable, you can use

./mill show sjsonnet[2.13.0].server.assembly

By default, the Sjsonnet background server lives in ~/.sjsonnet, and lasts 5 minutes before shutting itself when inactive.

Since the Sjsonnet client still has 0.2-0.3s of overhead, if using Sjsonnet heavily it is still better to include it in your JVM classpath and invoke it programmatically via new Interpreter(...).interpret(...).

Publishing

To publish, make sure the version number in build.sc is correct, then run the following commands:

./mill -i mill.scalalib.PublishModule/publishAll --sonatypeCreds lihaoyi:$SONATYPE_PASSWORD --publishArtifacts __.publishArtifacts --release true

./mill -i show sjsonnet[2.13.4].js.fullOpt
./mill -i show sjsonnet[2.13.4].jvm.assembly

Changelog

0.4.4

  • Update Mill to 0.10.12
  • Fix parsing of k/v cli arguments with an "=" in the value

0.4.2

  • Make lazy initialization of static Val.Obj thread-safe #136
  • Deduplicate strings in the parser #137
  • Update the JS example #141

0.4.1

  • Additional significant performance improvements #119
  • Error handling fixes and improvements #125

0.4.0

  • Performance improvements with lots of internal changes #117

0.3.3

  • Bump uJson version to 1.3.7

0.3.2

  • Bump uJson version to 1.3.0

0.3.1

  • Avoid catching fatal exceptions during evaluation

0.3.0

  • Add --yaml-debug flag to add source-line comments showing where each line of YAML came from #105#105
  • Add objectValues and objectVlauesAll to stdlib #104

0.2.8

  • Allow direct YAML output generation via --yaml-out
  • Do not allow duplicate field in object when evaluating list list comprehension #100
  • Fix compiler crash when '+' signal is true in a field declaration inside a list comprehension #98
  • Fix error message for too many arguments with at least one named arg #97

0.2.7

  • Streaming JSON output to disk for lower memory usage #85
  • Static detection of duplicate fields #86
  • Strict mode to disallow error-prone adjacent object literals #88

0.2.6

  • Add std.flatMap, std.repeat, std.clamp, std.member, std.stripChars, std.rstripChars, std.lstripChars

0.2.4

  • Add support for syntactical key ordering #53
  • Bump dependency versions

0.2.2

  • Bump verion of Scalatags, uPickle

0.1.9

  • Bump version of FastParse

0.1.8

  • Bump versions of OS-Lib, uJson, Scalatags

0.1.7

  • Support std lib methods that take a key lambda #40
  • Handle hex in unicode escaoes #41
  • Add encodeUTF8, decodeUTF8 std lib methdos #42
  • Properly fail on non-boolean conditionals #44
  • Support YAML-steam output #45

0.1.6

  • ~2x performance increase

0.1.5

  • Javascript support, allowing Sjsonnet to be used in the browser or on Node.js
  • Performance improvements

0.1.4

  • Scala 2.13 support
  • Performance improvements

0.1.3

  • Add std.mod, std.min and std.max
  • Performance improvements

0.1.2

  • Improvements to error reporting when types do not match

0.1.1

  • Performance improvements to the parser via upgrading to Fastparse 2.x

0.1.0

  • First release

More Repositories

1

learning-spark

Example code from Learning Spark book
Java
3,864
star
2

koalas

Koalas: pandas API on Apache Spark
Python
3,330
star
3

Spark-The-Definitive-Guide

Spark: The Definitive Guide's Code Repository
Scala
2,678
star
4

scala-style-guide

Databricks Scala Coding Style Guide
2,673
star
5

spark-deep-learning

Deep Learning Pipelines for Apache Spark
Python
1,993
star
6

click

The "Command Line Interactive Controller for Kubernetes"
Rust
1,416
star
7

LearningSparkV2

This is the github repo for Learning Spark: Lightning-Fast Data Analytics [2nd Edition]
Scala
1,158
star
8

megablocks

Python
1,147
star
9

spark-sklearn

(Deprecated) Scikit-learn integration package for Apache Spark
Python
1,080
star
10

spark-csv

CSV Data Source for Apache Spark 1.x
Scala
1,051
star
11

tensorframes

[DEPRECATED] Tensorflow wrapper for DataFrames on Apache Spark
Scala
749
star
12

devrel

This repository contains the notebooks and presentations we use for our Databricks Tech Talks
HTML
687
star
13

reference-apps

Spark reference applications
Scala
648
star
14

spark-redshift

Redshift data source for Apache Spark
Scala
598
star
15

spark-sql-perf

Scala
543
star
16

spark-avro

Avro Data Source for Apache Spark
Scala
538
star
17

spark-xml

XML data source for Spark SQL and DataFrames
Scala
501
star
18

spark-corenlp

Stanford CoreNLP wrapper for Apache Spark
Scala
424
star
19

mlops-stacks

This repo provides a customizable stack for starting new ML projects on Databricks that follow production best-practices out of the box.
Python
415
star
20

spark-training

Apache Spark training material
Scala
396
star
21

databricks-cli

(Legacy) Command Line Interface for Databricks
Python
384
star
22

spark-perf

Performance tests for Apache Spark
Scala
372
star
23

delta-live-tables-notebooks

Python
334
star
24

terraform-provider-databricks

Databricks Terraform Provider
Go
333
star
25

spark-knowledgebase

Spark Knowledge Base
328
star
26

databricks-ml-examples

Python
284
star
27

jsonnet-style-guide

Databricks Jsonnet Coding Style Guide
205
star
28

dbt-databricks

A dbt adapter for Databricks.
Python
199
star
29

databricks-sdk-py

Databricks SDK for Python (Beta)
Python
185
star
30

containers

Sample base images for Databricks Container Services
Dockerfile
163
star
31

databricks-sql-python

Databricks SQL Connector for Python
Python
158
star
32

sbt-spark-package

Sbt plugin for Spark packages
Scala
150
star
33

notebook-best-practices

An example showing how to apply software engineering best practices to Databricks notebooks.
Python
116
star
34

databricks-vscode

VS Code extension for Databricks
TypeScript
114
star
35

benchmarks

A place in which we publish scripts for reproducible benchmarks.
Python
106
star
36

terraform-databricks-examples

Examples of using Terraform to deploy Databricks resources
HCL
103
star
37

spark-tfocs

A Spark port of TFOCS: Templates for First-Order Conic Solvers (cvxr.com/tfocs)
Scala
88
star
38

intellij-jsonnet

Intellij Jsonnet Plugin
Java
82
star
39

sbt-databricks

An sbt plugin for deploying code to Databricks Cloud
Scala
71
star
40

terraform-databricks-lakehouse-blueprints

Set of Terraform automation templates and quickstart demos to jumpstart the design of a Lakehouse on Databricks. This project has incorporated best practices across the industries we work with to deliver composable modules to build a workspace to comply with the highest platform security and governance standards.
Python
71
star
41

spark-integration-tests

Integration tests for Spark
Scala
68
star
42

genai-cookbook

Python
63
star
43

spark-pr-dashboard

Dashboard to aid in Spark pull request reviews
JavaScript
54
star
44

run-notebook

TypeScript
47
star
45

ide-best-practices

Best practices for working with Databricks from an IDE
Python
47
star
46

unity-catalog-setup

Notebooks, terraform, tools to enable setting up Unity Catalog
45
star
47

simr

Spark In MapReduce (SIMR) - launching Spark applications on existing Hadoop MapReduce infrastructure
Java
44
star
48

devbox

Scala
38
star
49

databricks-sql-go

Golang database/sql driver for Databricks SQL.
Go
35
star
50

diviner

Grouped time series forecasting engine
Python
33
star
51

cli

Databricks CLI
Go
32
star
52

tmm

Python
30
star
53

security-bucket-brigade

JavaScript
30
star
54

databricks-sdk-go

Databricks SDK for Go
Go
29
star
55

pig-on-spark

proof-of-concept implementation of Pig-on-Spark integrated at the logical node level
Scala
28
star
56

databricks-sql-cli

CLI for querying Databricks SQL
Python
27
star
57

automl

Python
26
star
58

databricks-sql-nodejs

Databricks SQL Connector for Node.js
TypeScript
24
star
59

tpch-dbgen

Patched version of dbgen
C
22
star
60

als-benchmark-scripts

Scripts to benchmark distributed Alternative Least Squares (ALS)
Scala
22
star
61

spark-package-cmd-tool

A command line tool for Spark packages
Python
18
star
62

congruity

The goal of this library is to provide a compatibility layer that makes it easier to adopt Spark Connect. The library is designed to be simply imported in your application and will then monkey-patch the existing API to provide the legacy functionality.
Python
16
star
63

python-interview

Databricks Python interview setup instructions
15
star
64

xgb-regressor

MLflow XGBoost Regressor
Python
15
star
65

databricks-accelerators

Accelerate the use of Databricks for customers [public repo]
Python
15
star
66

tableau-connector

Scala
12
star
67

files_in_repos

Python
12
star
68

upload-dbfs-temp

TypeScript
12
star
69

spark-sklearn-docs

HTML
11
star
70

sqltools-databricks-driver

SQLTools driver for Databricks SQL
TypeScript
11
star
71

genomics-pipelines

secondary analysis pipelines parallelized with apache spark
Scala
10
star
72

workflows-examples

10
star
73

databricks-sdk-java

Databricks SDK for Java
Java
10
star
74

dais-cow-bff

Code for the "Path to Production" DAIS 2024 and 2023 talks
Jupyter Notebook
8
star
75

xgboost-linux64

Databricks Private xgboost Linux64 fork
C++
8
star
76

mlflow-example-sklearn-elasticnet-wine

Jupyter Notebook
7
star
77

databricks-ttyd

C
6
star
78

setup-cli

Sets up the Databricks CLI in your GitHub Actions workflow.
Shell
4
star
79

terraform-databricks-mlops-aws-project

This module creates and configures service principals with appropriate permissions and entitlements to run CI/CD for a project, and creates a workspace directory as a container for project-specific resources for the Databricks AWS staging and prod workspaces.
HCL
4
star
80

jenkins-job-builder

Fork of https://docs.openstack.org/infra/jenkins-job-builder/ to include unmerged patches
Python
4
star
81

terraform-databricks-mlops-azure-project-with-sp-creation

This module creates and configures service principals with appropriate permissions and entitlements to run CI/CD for a project, and creates a workspace directory as a container for project-specific resources for the Azure Databricks staging and prod workspaces. It also creates the relevant Azure Active Directory (AAD) applications for the service principals.
HCL
4
star
82

terraform-databricks-sra

The Security Reference Architecture (SRA) implements typical security features as Terraform Templates that are deployed by most high-security organizations, and enforces controls for the largest risks that customers ask about most often.
HCL
4
star
83

databricks-empty-ide-project

Empty IDE project used by the VSCode extension for Databricks
3
star
84

databricks-repos-proxy

Python
2
star
85

databricks-asset-bundles-dais2023

Python
2
star
86

pex

Fork of pantsbuild/pex with a few Databricks-specific changes
Python
2
star
87

SnpEff

Databricks snpeff fork
Java
2
star
88

notebook_gallery

Jupyter Notebook
2
star
89

terraform-databricks-mlops-aws-infrastructure

This module sets up multi-workspace model registry between a Databricks AWS development (dev) workspace, staging workspace, and production (prod) workspace, allowing READ access from dev/staging workspaces to staging & prod model registries.
HCL
2
star
90

expectations

Python
1
star
91

homebrew-tap

Homebrew Tap for the Databricks CLI
Ruby
1
star
92

terraform-databricks-mlops-azure-infrastructure-with-sp-creation

This module sets up multi-workspace model registry between an Azure Databricks development (dev) workspace, staging workspace, and production (prod) workspace, allowing READ access from dev/staging workspaces to staging & prod model registries. It also creates the relevant Azure Active Directory (AAD) applications for the service principals.
HCL
1
star
93

mfg_dlt_workshop

DLT Manufacturing Workshop
Python
1
star
94

databricks-dbutils-scala

The Scala SDK for Databricks.
Scala
1
star
95

kdd24-forecasting-anomaly-detection

Python
1
star
96

terraform-databricks-mlops-azure-project-with-sp-linking

This module creates and configures service principals with appropriate permissions and entitlements to run CI/CD for a project, and creates a workspace directory as a container for project-specific resources for the Azure Databricks staging and prod workspaces. It also links pre-existing Azure Active Directory (AAD) applications to the service principals.
HCL
1
star
97

terraform-databricks-mlops-azure-infrastructure-with-sp-linking

This module sets up multi-workspace model registry between an Azure Databricks development (dev) workspace, staging workspace, and production (prod) workspace, allowing READ access from dev/staging workspaces to staging & prod model registries. It also links pre-existing Azure Active Directory (AAD) applications to the service principals.
HCL
1
star