\documentclass[12pt, oneside]{article}

\usepackage{float}
\usepackage{lineno}
\usepackage{color, amssymb, amsmath, amsthm, verbatim, wasysym}
\usepackage{natbib}
\usepackage{epsfig}
\usepackage[mathscr]{eucal}
\usepackage{mathrsfs}
\usepackage{appendix}
\raggedbottom
\usepackage[left=0.8in,right=0.8in,top=0.8in,bottom=0.9in,centering]{geometry}

% Uncomment to show references.
%\usepackage[notcite,notref]{showkeys}

% To make really wide hats that cover everything:
\usepackage{scalerel}
\usepackage{stackengine}
\setstackEOL{\#}
\stackMath
\def\hatgap{1pt}
\def\subdown{-0.2pt}
\newcommand\reallywidehat[2][]{%
\renewcommand\stackalignment{l}%
\stackon[\hatgap]{#2}{%
\stretchto{%
    \scalerel*[\widthof{$#2$}]{\kern-.6pt\bigwedge\kern-.6pt}%
    {\rule[-\textheight/2]{1ex}{\textheight}}%WIDTH-LIMITED BIG WEDGE
}{0.6ex}% THIS SQUEEZES THE WEDGE TO 0.5ex HEIGHT
_{\smash{\belowbaseline[\subdown]{\scriptstyle#1}}}%
}}

% For a 'strut' that creates space above underbraces
\newcommand*\mystrut[1]{\vrule width0pt height0pt depth#1\relax}

% Punctuation
\newcommand{\com}{\, ,}
\newcommand{\per}{\, .}

% A nice 'definition'
\newcommand{\defn}{\ensuremath{\stackrel{\mathrm{def}}{=}}}

% Use \bar to over line solo symbols
\newcommand{\av}[1]{\left \langle{#1} \right \rangle}
\newcommand{\avbg}[1]{\overline{#1}}
\newcommand{\avbgg}[1]{\overline{#1}}
\newcommand{\hav}[1]{\widehat{#1}}

% Begin and end equations
\newcommand{\beq}{\begin{equation}}
\newcommand{\eeq}{\end{equation}}

% Vector calculus operators
\newcommand{\p}{\partial}
\newcommand{\bnabla}{\boldsymbol \nabla}
\newcommand{\pnabla}{\boldsymbol \nabla_{\! \! \perp}}
\newcommand{\hnabla}{\bnabla_{\! \! h}}
\newcommand{\bnablad}{\bnabla_{\! \! \alpha}}
\newcommand{\bcdot}{\boldsymbol \cdot}
\newcommand{\hlap}{\triangle_h}
\newcommand{\lap}{\triangle}
\newcommand{\grad}{\bnabla}
\newcommand{\curl}{\bnabla \!\times\!}
\newcommand{\diver}{\bnabla \bcdot }
\newcommand{\cross}{\times}

% Bold symbolds
\newcommand{\bu}{\boldsymbol u}
\newcommand{\buh}{\boldsymbol u_h}
\newcommand{\bx}{\boldsymbol x}
\newcommand{\ba}{\boldsymbol{a}}
\newcommand{\bk}{\boldsymbol{k}}
\newcommand{\bh}{\boldsymbol{h}}
\newcommand{\bm}{\boldsymbol{m}}
\newcommand{\bn}{\boldsymbol{\hat n}}
\newcommand{\bxh}{\hspace{0.1em} \boldsymbol{\hat x}}
\newcommand{\byh}{\hspace{0.1em}\boldsymbol{\hat y}}
\newcommand{\bzh}{\hspace{0.1em}\boldsymbol{\hat z}}
\newcommand{\bnh}{\hspace{0.1em}\boldsymbol{\hat n}}
\newcommand{\bomega}{\boldsymbol \omega}
\newcommand{\bOmega}{\boldsymbol \Omega}
\newcommand{\bxi}{\ensuremath {\boldsymbol {\xi}}}
\newcommand{\bXi}{\ensuremath {\boldsymbol {\Xi}}}
\newcommand{\bU}{\boldsymbol{U}}
\newcommand{\bX}{\boldsymbol{X}}

% Greek abbrevs
\newcommand{\ep}{\epsilon}
\newcommand{\om}{\omega}
\newcommand{\kap}{\kappa}

% Roman characters
\newcommand{\ee}{\mathrm{e}}
\newcommand{\ii}{\mathrm{i}}
\newcommand{\cc}{\mathrm{cc}}
\newcommand{\dd}{{\rm d}}
\newcommand{\id}{{\, \rm d}}
\newcommand{\DD}{{\rm D}}
\newcommand{\J}{\mathrm{J}}
\renewcommand{\L}{\mathrm{L}}

% Non-dimensional numbers
\newcommand{\Ri}{Ri}
\newcommand{\Ro}{Ro}
\newcommand{\Bu}{Bu}
\newcommand{\Pe}{Pe}

% Material derivative
\newcommand{\Dt}[1]{\mathrm{D}_t #1}

% Small in-line fractions
\newcommand{\half}{\tfrac{1}{2}}

% Bold 'F' for 'forcing'
\newcommand{\bff}{\boldsymbol{F}}
\newcommand{\fh}{\breve f}

% Dissipation operator
\newcommand{\friction}{\mathrm{F}}
\newcommand{\mixing}{\mathrm{M}}

\newcommand{\mode}{\phi}
\newcommand{\q}{\tilde q}
\newcommand{\qpsi}{\tilde \psi}

\begin{document}

\title{\vspace{-4ex} Quasi-geostrophic flow with tracers}
\author{Greg}
\date{} \maketitle \vspace{-4ex}

\section{Preliminaries}

More or less according to Vallis (2006), two-layer quasi-geostrophic flow is governed by the equations
\begin{align}
\q_{1t} + \J \big ( \qpsi_1, \q_1 \big ) &= \friction \big ( \hlap \qpsi_1 \big ) \\
\q_{2t} + \J \big ( \qpsi_2, \q_2 \big ) &= -r \hlap \qpsi_2 + \friction  \big( \hlap \qpsi_2 \big ) \com
\end{align}
where the potential vorticities $Q_i$ are defined by
\begin{align}
\q_{1} &= \hlap \qpsi_1 - F_1 \big ( \qpsi_1 - \qpsi_2 \big ) + \beta y \com \\
\q_2 &= \hlap \qpsi_2 + F_2 \big ( \qpsi_1 - \qpsi_2 \big ) + \beta y \com
\end{align}
and the Burger numbers $F_1$ and $F_2$ are defined by $F_i = f_0^2 / g' H_i$, where $H_i$ is the height of layer $i$ and $g'$ is the reduced gravity. The number of parameters in the problem are reduced if the deformation `radius' $R$ and layer depth ratio $\delta$ are defined through
\beq
R^2 \defn \frac{g' H_1 H_2}{f_0^2 \left ( H_1 + H_2 \right )} \com \qquad \text{and} \qquad \delta \defn \frac{H_1}{H_2} \com
\eeq
so that
\beq
F_1 = \frac{R^{-2}}{1 + \delta} \com \qquad \text{and} \qquad F_2 = \frac{\delta R^{-2}}{1 + \delta} \per
\eeq
We decompose $\qpsi_i$ into $\qpsi_i = - U_i y + \psi_i$, so that
\begin{align}
\q_1 &= \underbrace{\mystrut{1.4ex}  \beta y + F_1 \big ( U_1 - U_2 \big )y}_{\defn Q_1} + \underbrace{\mystrut{1.4ex} \hlap \psi_1 - F_1 ( \psi_1 - \psi_2 )}_{\defn q_1} \com \\
\q_2 &= \underbrace{\mystrut{1.4ex}  \beta y - F_2 \big ( U_1 - U_2 \big )y}_{\defn Q_2} + \underbrace{\mystrut{1.4ex} \hlap \psi_2 + F_2 ( \psi_1 - \psi_2 )}_{\defn q_2} \com
\end{align}
The potential vorticity conservation equations become
\begin{align}
q_{1t} + \J \left( \psi_1, q_1 \right ) + U_1 q_{1x} + \psi_{1x} Q_{1y} &= \friction \left ( \hlap \psi_1 \right) \com \\
 q_{2t} + \J \left( \psi_2, q_2 \right ) + U_2 q_{2x} + \psi_{2x} Q_{2y} &= - r \hlap \psi_2 + \friction \left ( \hlap \psi_2 \right) \per
\end{align}

\section{Streamfunction inversion}

The streamfunction-vorticity relationship is usefully expressed in matrix form,
\beq
\left [ \, \begin{matrix}
q_1 \\
q_2 \\
\end{matrix} \, \right ] = \underbrace{ \mystrut{3ex} \left [ \,
\begin{matrix}
\hlap - F_1 & - F_1 \\
- F_2 & \hlap - F_2 \\
\end{matrix} \, \right ]}_{\defn \mathsf{M}} \left [ \, \begin{matrix}
\psi_1 \\
\psi_2 \\
\end{matrix} \, \right ]
\eeq
Which, in Fourier space, reads
\beq
\left [ \, \begin{matrix}
\hat q_1 \\
\hat q_2 \\
\end{matrix} \, \right ] = - \left [ \,
\begin{matrix}
K^2 + F_1 & F_1 \\
F_2 & K^2 + F_2  \\
\end{matrix} \, \right ] \left [ \, \begin{matrix}
\hat \psi_1 \\
\hat \psi_2 \\
\end{matrix} \, \right ]
\eeq
Noting that $\left ( K^2 + F_1 \right ) \left ( K^2 + F_2 \right ) - F_1 F_2 = K^2 \left ( K^2 + F_1 + F_2 \right )$, the inversion of $\mathsf{M}$ in Fourier space yields
\beq
\mathsf{M}^{-1} = \frac{1}{K^2 \left ( K^2 + F_1 + F_2 \right )} \left [ \,
\begin{matrix}
- \left ( K^2 + F_2 \right ) & F_1 \\
F_2 & - \left (K^2 + F_1\right ) \\
\end{matrix} \, \right ] \per
\eeq

\section{Two-layer tracers}

The two-layer tracer equations are
\begin{align}
c_{1t} + \J \left ( \psi_1, c_1 \right ) + U_1 c_{1x} &= - \kappa \left ( c_1 - c_2 \right ) + \mixing c_1 \com \\
c_{2t} + \J \left ( \psi_2, c_2 \right ) + U_2 c_{2x} &=  \kappa \left ( c_1 - c_2 \right ) + \mixing c_2
\end{align}

\section{Numerics}

When we compute the right hand side, we either dealias or use an exponential filter of the form
\beq
\mathscr{F} = \exp \Big \{ - d \left [ \left ( k / k_c \right )^2 + \left ( \ell / \ell_c \right )^2 - 1 \right ]^{n/2} \Big \} \per
\eeq

\bibliographystyle{jfm}
\bibliography{refs}

\end{document}


% !TEX root=../presentation_1.tex
\section{Method}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item Idea: use better BFS broadcasting structure.
    \item Like \textbf{GHS}, still merging components, but now use an auxillary BFS tree to coordinate - $O(D)$.
    \item Suppose we have an $(n/k,O(k))$-MST forest $\mathcal{F}$ using GHS.
    \item At most $n/k$ fragments, diameter $O(k)$.
    \item $O(k \log^*n)$ rounds with $O(m + k \log n)$ messages.
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item Build an auxillary BFS tree $\tau$.
    \item $O(D)$ time and $O(m)$ messages.
    \item Each node compute the BFS interval.
    \begin{itemize}
        \item One convergecast to count the number of leaves under each node.
        \item One broadcast to assign interval.
        \item $O(D)$ time and $O(n)$ messages.
    \end{itemize}
    \item Interval is computed so that we know how to route messages from the root to any base fragment F
\end{itemize}
\begin{figure}
\centering
\includegraphics[width=0.4\textwidth,trim={0cm 5cm 12cm 0},clip]{figures/bfstree.pdf}
\includegraphics[width=0.4\textwidth,trim={0cm 10cm 20cm 0},clip]{figures/interval.pdf}
\end{figure}
\end{frame}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item Finally conduct a pipelined convergecast and the root learns the intervals of all the base fragments. Sends messages of the maximum interval of each fragment.
    \item Takes $O(D+\frac{n}{k})$ and $O(D \cdot \frac{n}{k})$ messages. (Need to aggregate messages of one fragment at a time.)
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item To send the fragment ID: $O(1)$ rounds and $O(m)$ messages.
    \item To convergecast the $\frac{n}{k}$ fragment IDs: $O(D+\frac{n}{k})$ rounds and $O(D \cdot\frac{n}{k})$ messages.
    \item Assume each vertex knows its fragment ID, and also the fragments IDs of its neighbors
    \item We can compute MWOE locally, and send to the root of the fragment
    \item Now suppose $D \le \sqrt{n}$, and we select $k=\sqrt{n}$.
    \item $O(k)=O(\sqrt{n})$ rounds and $O(n)$ messages.
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item Perform a \textbf{pipelined convergecast} to the root, send MWOE of each component.
    \item $O(D+\frac{n}{k})$ rounds and $O(D \cdot \frac{n}{k})$ messages.
    \item Then the root tells each fragment which one to merge with.
    \item Sends message $<F,F'>$ through pipelined broadcast, to tell $F$ to merge with $F'$.
    \item The node that receives merge message, changes the fragment ID.
    \item $O(D+\frac{n}{k})$ rounds and $O(D \cdot \frac{n}{k})$ messages.
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item Finally, every vertex notifies its neighbors about the change in fragment ID.
    \item $O(1)$ rounds and $O(m)$ messages.
    \item Round: $O(D+\frac{n}{k}) + O(k\log^* n) + O((D + k + \frac{n}{k})\log n) = O(\sqrt{n}\log n)$.
    \item Message: $O(E \log n + n\log n \cdot \log^* n)$
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{A Simple Deterministic Algorithm [Elk17]}
\begin{itemize}
    \item If $D > \sqrt{n}$, then let $k=D$.
    \item $O(D+\frac{n}{k}) + O(k\log^* n) + O((D + k + \frac{n}{k})\log n) = O(D\log n)$ rounds
    \item The number of messages is the same as before.
    \item Round: $O((D + \sqrt{n})\log n)$
    \item Message: $O(E \log n + n\log n \cdot \log^* n)$
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{Conclusion}
\begin{itemize}
    \item Near optimal time and message complexities.
    \item A fully deterministic algorithm.
\end{itemize}

\input{sections/table}
\end{frame}


\chapter{Discussion and Conclusions}\label{ch:discussion}

\lang is neither perfect nor complete:
the nature of the syntactic model requires that inductives live in a universe
higher than that in which their corresponding unsized types would live,
and it's missing features such as an infinite size and coinductives.
In this chapter, I discuss some of these shortcomings
and give some possible directions for future work based on them.

\section{The Infinite Size} \label{sec:infinity}

In prior sized type systems, the infinite size\index{infinite size} $\infty$ is applied to sized inductive types
to represent a ``full'' inductive type encompassing that inductive at all sizes,
which essentially corresponds to the usual unsized inductive.
Whereas an inductive of some size $s$ can be thought of as the type of elements
with at most $s$ many layers of constructors,
the full inductive can be thought of as the type of elements with any number of layers of constructors.

The infinite size is characterized by its subsizing behaviour:
$\subsize*{s}{\infty}$ holds for \emph{any} $s$.
This includes its own successor, \ie $\subsize*{\sss{\infty}}{\infty}$,
leading to non--well-founded sequences of strictly ``decreasing'' sizes:
$\dots < \infty < \infty < \infty$.
Naturally, there's no way to model the infinite size as an element of $\SizeT$
given that I've shown that $\SizeT$s \emph{are} well founded.
If there were, then it'd be possible to prove an inconsistency.
Let $\inftyT$ be the translation of $\infty$,
and let $\inftyltinfty$ be the translation of $\subsize*{\sss{\infty}}{\infty}$.
\begin{align*}
&\LetT{\tg{{\neg}wf\inftyT}}{\arrT*{\app{\AccT}{\inftyT}}{\botT}}{\funT{\mathit{acc}}{\app{\AccT}{\inftyT}}{\matchT*{\mathit{acc}}{\app{\accT}{p} \RightarrowT \app{p}{\inftyT}{\inftyltinfty}}}} \\
&\LetT{\tg{false}}{\botT}{\app{\tg{{\neg}wf\inftyT}}{(\app{\accessible}{\inftyT})}}
\end{align*}

In set-theoretic models of sized type systems with an infinite size,
sizes are modelled as set-theoretic (transfinite) ordinals,
the infinite size isn't modelled as a single ordinal;
instead, for each use of the infinite size,
its set-theoretic interpretation is an ordinal that is ``large enough'' in that context.
For instance, the interpretation of the infinite size of $\N{\infty}$
is the first limit ordinal $\omega$.

This strategy doesn't adapt well to \lang with its size abstractions and syntactic model\index{syntactic model},
since it requires a non-local translation of sizes.
For instance, given the size application $\App{e}{\infty}$,
what $\infty$ translates to would hypothetically depend on what $e$ translates to,
and likely require further static analysis of $\compile{e}$ beyond a simple translation
over typing derivations.

Since the motivation for having the infinite size is specifically for representing full inductives,
one alternative could be to define the full inductive separately
and provide functions to and from the corresponding sized inductive,
such as the following for $\W*$.
\begin{align*}
& \data{\App{\app{\W*}{(\annot{A}{\Type{i}})}{(\annot{B}{\arr*{A}{\Type{i}}})}}{\infty}}{\Type{i+1}} \\
& \quad \annot{\constr{sup\infty}}{\arr{x}{A}{\arr*{(\arr*{\app{B}{x}}{\app{\App{\W*}{\infty}}{A}{B}})}{\App{\app{\W*}{A}{B}}{\infty}}}}
\end{align*}

Defining a function from $\W{x}{A}{B}{s}$ to $\W{x}{A}{B}{\infty}$ is trivial,
since we're discarding size information.
What about going from $\W{x}{A}{B}{\infty}$ to $\W{x}{A}{B}{s}$?
What should $s$ be?
The size algebra could be augmented to be able to represent transfinite ordinals
so that $s$ is again a size that is ``large enough'',
but we can hardly expect programmers to manipulate ordinals,
and I conjecture that we would lose any hope of deciding $\subsize*{}{}$
without any user intervention.

The key insight is that what's important about an element of a full inductive
isn't its precise size and depth of constructors,
but merely that it has \emph{some} unknown size.
Another alternative to the infinite size, then, could be to represent a full inductive
as an existentially-quantified sized inductive,
\ie $\Pairtype{\alpha}{\N{\alpha}}$ and $\Pairtype{\alpha}{\W{x}{A}{B}{\alpha}}$.
We've already seen existential sizes in action: they're in the return types of $\qsort$ and $\msort$.

There is still a limitation similar to that in \cref{sec:examples:limitations}
when trying to represent the constructors of full inductives.
For $\Pairtype{\alpha}{\W{x}{A}{B}{\alpha}}$, we need a ``constructor'' of the following type.
\begin{align*}
\annot{\const{sup'}}{\arr{x}{A}{\arr*{(\arr*{B}{\Pairtype{\alpha}{\W{x}{A}{B}{\alpha}}})}{\Pairtype{\alpha}{\W{x}{A}{B}{\alpha}}}}}
\end{align*}
All we need is a function
$$\annot{\const{ac}}{\arr{x}{A}{\arr*{(\arr*{B}{\Pairtype{\alpha}{\W{x}{A}{B}{\alpha}}})}{\Pairtype{\alpha}{(\arr*{B}{\W{x}{A}{B}{\alpha}})}}}}$$
and we're good to go.
\begin{align*}
\app{\const{sup'}}{x}{f} =
\unpair*{\alpha}{f'}{\app{\const{ac}}{x}{f}}{\Pair{\sss{\alpha}}{\sup{x}{A}{B}{\sss{\alpha}}{\alpha}{x}{f'}}}
\end{align*}

Unfortunately, as the name might suggest,
$\const{ac}$ is an instance of the axiom of choice\punctstack{,}%
\footnote{The ``choice'' made here is the existentially-quantified size in the consequent:
the axiom asserts that there's always a way to choose a size such that
all of the well-founded trees returned have that size.}
which for weak existentials\index{weak dependent pair} (whose elements we can't project out)
is nonconstructive,
so there's no hope of implementing $\const{ac}$.
However, if we take weak existentials as a primitive of \lang
rather than being defined as an encoding,
and model them by strong dependent pairs in \CICE,
then the translation of $\const{ac}$ \emph{can} be implemented as a function,
also making use of the limit operator.
In other words, the syntactic model\index{syntactic model} justifies the axiom $\const{ac}$ in the source.
The mechanization of $\compile{\const{ac}}$ in Agda and Coq are given in
\cref{app:mechanization:agda:W} and \cref{app:mechanization:coq:W}, respectively.

Nevertheless, $\const{ac}$ remains a noncomputing axiom
unless the size algebra is augmented to include a limit operator
and size expressions consequently treated as regular terms.
There is no way to represent generalized full inductives as
sized inductives existentially quantified by sizes
and faithfully define their constructors without losing either
decidability of subsizing from exposing the underlying ordinal representation of sizes,
or canonicity from the inclusion of a noncomputing axiom.
Representing ordinary full inductives (namely naturals) this way,
however, has been previously explored~\citep{guarded, modal-sizes}.

\section{Universe Levels of Inductives} \label{sec:universe-levels}

The universes in which the type of natural numbers and W types in \lang live
are, in a sense, one level\index{universe level} higher than is usually expected;
their typing rules are reproduced below.
$\N*$ is typically in $\Type{0}$,
while $\W*$ is typically in $U$ rather than $\axioms{U}$.
\begin{mathpar}
\inferrule[\rref*{nat}]{
  \wf{\Phi}{\Gamma} \\
  \wf{\Phi}{s}
}{
  \infer{\Phi; \Gamma}{\N{s}}{\Type{1}}
}
\and
\inferrule[\rref*{wft}]{
  \wf{\Phi}{s} \\
  \infer{\Phi; \Gamma}{\sigma}{U} \\\\
  \infer{\Phi; \Gamma, \annot{x}{\sigma}}{\tau}{U}
}{
  \infer{\Phi; \Gamma}{\W{x}{\sigma}{\tau}{s}}{\axioms{U}}
}
\end{mathpar}

This is due to how the translation is defined:
$\NatT$ and $\WT$ have a $\SizeT$ as parameter,
the $\limT$ operator quantifies over the type of the domain of its function argument,
and that type must be ``large'' enough to accommodate the correct type.
For $\app{\WT}{\sigmaT}{\tauT}{\sT}$,
the domain is $\app{\tauT}{\aT}$ for some $\aT$\punctstack{,}%
\footnote{For generalized inductives, given a recursive argument in the form of a function,
the domain of $\limT$ should encompass the domain of that function.}
as is the case for the definition of $\compile{\const{ac}}$,
so if its universe is $\TypeT{\iT}$,
then the universe of the type of $\sT$ must be $\TypeT{\tg{i+1}}$,
according to the definition of $\SizeT$, reproduced below.

\begin{align*}
&\dataT{\SizeT}{\TypeT{\tg{i+1}}} \\
&\quad \annotT{\sucT}{\arrT*{\SizeT}{\SizeT}} \\
&\quad \annotT{\limT}{\funtypeT{A}{\TypeT{\iT}}{\arrT*{(\arrT*{A}{\SizeT})}{\SizeT}}}
\end{align*}

This is a nonnegotiable condition:
defining $\SizeT$ to be in the same universe as that which $\limT$ quantifies over
leads to $\szltT$ no longer being well founded,
since in this hypothetical scenario $\SizeT$ itself could be applied to $\limT$
to define an $\inftyT$ size.
\begin{align*}
&\LetT{\inftyT}{\SizeT}{\app{\limT}{\SizeT}{(\funT{\xT}{\SizeT}{\xT})}} \\
&\LetT{\inftyltinfty}{\inftyT \szltT \inftyT}{\app{\coconeT}{\SizeT}{(\app{\sucT}{\inftyT})}{(\funT{\xT}{\SizeT}{\xT})}{(\app{\sucT}{\inftyT})}{(\app{\reflleq}{(\app{\sucT}{\inftyT})})}}
\end{align*}

One way to ``shrink'' the universe of $\SizeT$, so to speak,
could be to parametrize it over the type over which $\limT$ currently quantifies over,
yielding the following inductive definition.
\begin{align*}
&\dataT{\app{\SizeT}{(\annotT{A}{\TypeT{\iT}})}}{\TypeT{\iT}} \\
&\quad \annotT{\sucT}{\arrT*{\SizeT}{\SizeT}} \\
&\quad \annotT{\limT}{\arrT*{(\arrT*{A}{\SizeT})}{\SizeT}}
\end{align*}

The problem with this alternative is that for $\app{\WT}{\sigmaT}{\tauT}$,
the parameter of its size parameter would be $\app{\tauT}{\aT}$,
where $\annotT{\aT}{\sigmaT}$ is the third formal argument to its constructor $\supT$,
but this argument is only part of the constructor, not the type.
The intuition is that the parametrized $\SizeT$ is too restrictive
and there aren't ``enough'' sizes to cover all well-founded trees of any particular type.

In a sense, it's reasonable to expect that $\SizeT$ needs to live in a larger universe.
The r\^ole of $\SizeT$ is to represent all of the possible sizes of a given full inductive,
so we would expect $\SizeT$ to be just as large as the inductive itself.
Aside from situations where the inductive is impredicative\index{impredicativity}, \ie in $\PropT$,
parametrizing over $\SizeT$ then necessarily requires moving up a universe
so that it's not essentially quantifying over itself.

If having inductive types in the correct universe were more important than
the potential expressibility of infinitude,
we could eliminate $\limT$ altogether and model sizes as ordinary naturals.
Then $\SizeT$ would live in $\Type{0}$, $\NatT$ and $\WT$ would live in the correct universes,
as well as $\N*$ and $\W*$.
Although this would affect the judgements of both \lang and \CICE,
this wouldn't affect the proofs, since the changes are the same for both languages.
However, this does mean giving up $\const{ac}$
and likely any hope of defining any infinitary constructs like $\const{\omega}$
when using this model.

\section{Streams and Coinductives}

Dual to inductive types, coinductive types allow for constructing
potentially infinitely large elements in a principled manner,
and are present in many proof assistants such as Coq, Agda, and Idris.
Conventionally, while fixpoints are guarded by destructors\index{guardedness}
and destruct elements of inductives by recurring only on syntactically smaller elements,
cofixpoints are guarded by constructors and occur only as a syntactic argument to a constructor~\citep{guard}.
Since coinductives aren't present in pCIC\index{Calculus of Inductive Constructions!Predicative \textasciitilde},
upon which \CICE is based, I don't include them in \lang either,
as they would lack a translation in the syntactic model.
Nevertheless, we can speculate on how they might appear and interact with sizes.
Here, I define the classic example of coinductive streams,
composed of a head element and a tail stream.
\begin{mathpar}
\inferrule[\rlabel*{stream}]{
  \wf{\Phi}{s} \\
  \infer{\Phi; \Gamma}{\tau}{U}
}{
  \infer{\Phi; \Gamma}{\Stream{\tau}{s}}{U}
}
\and
\inferrule[\rlabel*{hd}]{
  \infer{\Phi; \Gamma}{e}{\Stream{\tau}{s}}
}{
  \infer{\Phi; \Gamma}{\shd{e}}{\tau}
}
\and
\inferrule[\rlabel*{tl}]{
  \infer{\Phi; \Gamma}{e}{\Stream{\tau}{s}}
}{
  \infer{\Phi; \Gamma}{\stl{e}}{\Funtype<{\alpha}{s}{\Stream{\tau}{\alpha}}}
}
\and
\inferrule[\rlabel*{scons}]{
  \infer{\Phi; \Gamma}{e_1}{\tau} \\
  \infer{\Phi, \bound{\alpha}{s}; \Gamma}{e_2}{\Stream{\tau}{\alpha}}
}{
  \infer{\Phi; \Gamma}{\scons{\alpha}{s}{e_1}{\alpha}{s}{e_2}}{\Stream{\tau}{s}}
}
\and
\inferrule[\rlabel*{cofix}]{
  \infer{\Phi, \alpha; \Gamma}{\sigma}{U} \\
  \fresh{\beta} \\
  \check{\Phi, \alpha; \Gamma, \annot{f}{\Funtype<{\beta}{\alpha}{\subst{\sigma}{\alpha}{\beta}}}}{e}{\sigma}
}{
  \infer{\Phi; \Gamma}{\cofix{f}{\alpha}{\sigma}{e}}{\Funtype{\alpha}{\sigma}}
}
\end{mathpar}

Just as the size of an inductive informally indicates at most how many layers of constructors its elements contain,
the size of a coinductive informally indicates \emph{at least} how many layers,
and in the case of $\app{\Stream*}{A}$, at least how many elements of $A$ it contains.
Of course, streams may contain an infinite number of elements,
so the analogy works better in the relative sense:
if a stream contains at least $s$ elements,
then its tail must contain at least $\bound{\alpha}{s}$, strictly fewer, elements.
The reduction rules of streams, omitted here, operate as expected:
$\shd{}$ projects out the head and $\stl{}$ projects out the tail.

To actually construct infinite streams, we need cofixpoint expressions.
The natural correspondence of guardedness\index{guardedness} in sized types
is that cofixpoint bodies must construct coinductives larger than
their own occurrences inside the body,
which coincides with the structure of \rref{fix}.
Cofixpoints also reduce when applied to a size that has some subsize,
just like fixpoints.
Interestingly, this suggests that cofixpoints might also be translated in the syntactic model
to well-founded induction\index{well-founded induction} on sizes despite constructing a coinductive type.

\clearpage % TODO: clearpage
With cofixpoints, we can then construct an infinite stream of some single element.
Let $A$ in the definitions to follow be some type.
\begin{align*}
& \Let{\dup}{\arr*{A}{\Funtype{\alpha}{\Stream{A}{\alpha}}}}{\\
& \quad \fun{a}{A}{\cofix{\dup*}{\alpha}{\Stream{A}{\alpha}}{\\
& \qquad \scons{\beta}{\alpha}{a}{\beta}{\alpha}{\App{\dup*}{\beta}}}}}
\end{align*}

Notice that the stream produced has \emph{any} size,
which can be interpreted as having ``at least'' any number of elements---a
truly infinite stream.
More generally, a coinductive universally quantified by size corresponds to a full coinductive,
dual to a inductive existentially quantified by a size corresponding to a full inductive.

We can manipulate sized streams as expected,
such as taking only the odd elements of a stream
or interleaving two streams by alternation.
\begin{align*}
& \Let{\odds}{\Funtype{\alpha}{\arr*{(\Funtype{\beta}{\Stream{A}{\beta}})}{\Stream{A}{\alpha}}}}{ \\
& \quad \cofix{\odds*}{\alpha}{\arr*{(\Funtype{\beta}{\Stream{A}{\beta}})}{\Stream{A}{\alpha}}}{ \\
& \qquad \fun{s}{\Funtype{\beta}{\Stream{A}{\beta}}}{\scons{\beta}{\alpha}{\shd{(\App{s}{\alpha})}}{\beta}{\alpha}{\app{\App{\odds*}{\beta}}{(\Fun{\gamma}{\App{\stl{(\App{\stl{(\App{s}{\sss{\sss{\gamma}}})}}{\sss{\gamma}})}}{\gamma}})}}}}} \\
\hfill \\
& \Let{\interleave}{\Funtype{\alpha}{\arr*{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}}}{ \\
& \quad \cofix{\interleave*}{\alpha}{\arr*{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}}{ \\
& \qquad \fun{s_1}{\Stream{A}{\alpha}}{\fun{s_2}{\Stream{A}{\alpha}}{\scons{\beta}{\alpha}{\shd{s_1}}{\beta}{\alpha}{ \\
& \qquad \quad \scons{\gamma}{\beta}{\shd{s_2}}{\gamma}{\beta}{\app{\App{\interleave*}{\alpha}}{(\App{\stl{s_1}}{\gamma})}{(\App{\stl{s_2}}{\gamma})}}}}}}}
\end{align*}

Just as with lists, we can write size-preserving functions on streams
and use them to define cofixpoints that would otherwise not pass syntactic guard checking.
One common example from Haskell is defining a stream of Fibonacci numbers using,
in our case, a size-preserving zipping function.
Suppose we have a function $\annot{f}{\arr*{A}{A}{A}}$ and some element $\annot{a}{A}$.
(For the actual Fibonacci numbers, $A$ would be the naturals, $f$ would be addition, and $a$ would be 1.)
\begin{align*}
& \Let{\zip}{\Funtype{\alpha}{\arr*{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}}}{ \\
& \quad \cofix{\zip*}{\alpha}{\arr*{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}{\Stream{A}{\alpha}}}{ \\
& \qquad \fun{s_1}{\Stream{A}{\alpha}}{\fun{s_2}{\Stream{A}{\alpha}}{ \\
& \qquad \quad \scons{\beta}{\alpha}{\app{f}{\shd{s_1}}{\shd{s_2}}}{\beta}{\alpha}{\app{\App{\zip*}{\beta}}{(\App{\stl{s_1}}{\beta})}{(\App{\stl{s_2}}{\beta})}}}}}}
\end{align*}

\begin{align*}
& \Let{\fibs}{\Funtype{\alpha}{\Stream{A}{\alpha}}}{ \\
& \quad \cofix{\fibs*}{\alpha}{\Stream{A}{\alpha}}{ \\
& \qquad \scons{\beta}{\alpha}{a}{\beta}{\alpha}{\scons{\gamma}{\beta}{a}{\gamma}{\beta}{\app{\App{\zip}{\gamma}}{(\App{\fibs*}{\gamma})}{(\App{\stl{(\App{\fibs*}{\beta})}}{\gamma})}}}}}
\end{align*}

Coinductive types in general can be implemented as record definitions
just as inductive types can be implemented as data definitions.
However, sized coinductives in Agda's standard library are implemented
in terms of a single coinductive $\Thunk{F}{s}$ record%
\footnote{See \textsf{Codata.Sized.Thunk} from the Agda standard library, URL \url{https://agda.github.io/agda-stdlib/Codata.Sized.Thunk.html}.}
with sized parameter $F$ and size $s$,
and all other coinductives are implemented as nested inductives,
where occurrences of the type in its constructors' types are wrapped around a $\Thunk*$.
\begin{mathpar}
\inferrule[\rlabel*{thunk}]{
  \wf{\Phi}{s} \\
  \infer{\Phi; \Gamma}{F}{\Funtype{\alpha}{U}}
}{
  \infer{\Phi; \Gamma}{\Thunk{F}{s}}{U}
}
\and
\inferrule[\rlabel*{force}]{
  \infer{\Phi; \Gamma}{e}{\Thunk{F}{s}}
}{
  \infer{\Phi; \Gamma}{\force{e}}{\Funtype<{\alpha}{s}{\App{F}{\alpha}}}
}
\and
\inferrule[\rlabel*{think}]{
  \infer{\Phi, \bound{\alpha}{s}; \Gamma}{e}{\App{F}{\alpha}}
}{
  \infer{\Phi; \Gamma}{\thunk{\alpha}{s}{e}}{\Thunk{F}{s}}
}
\end{mathpar}

This alternate technique is equally expressive,
since it allows encoding M types, the dual of W types, not just streams.
\begin{align*}
& \data{\Stream{(\annot{A}{\Type{i}})}{\alpha}}{\Type{i+1}} \\
& \quad \annot{\scons*}{\arr*{A}{\Thunk{(\app{\Stream*}{A})}{\alpha}}{\Stream{A}{\alpha}}} \\
\hfill \\
& \data{\App{\app{\M*}{(\annot{A}{\Type{i}})}{(\annot{B}{\arr*{A}{\Type{i}}})}}{\alpha}}{\Type{i+1}} \\
& \quad \annot{\inf*}{\arr{a}{A}{\arr*{(\arr*{\app{B}{a}}{\Thunk{(\app{\M*}{A}{B})}{\alpha}})}{\App{\app{\M*}{A}{B}}{\alpha}}}}
\end{align*}

\section{Designing for Syntactic Modelling}

Choosing to use a syntactic model imposes some constraints on the design
of the source and target languages, as well as on the proof architecture.
Most notably, proof of correctness of syntactic models proceed
by induction on the source derivations,
so \lang uses untyped conversion to avoid a dependency between typing and definitional equality,
which would otherwise require a large and complex mutually inductive proof of type preservation.

\iffalse
Strictly speaking, such a proof would still be possible,
since the compositionality lemmas are merely up to syntactic equality.
If they were instead up to typed equivalence
(as is the case for the translations in \citet{wjb}),
then the base cases would fail:
to show
$\defeq{\compile{\Phi}, \compile{\Gamma}}{\yT}{\yT}{\compile{\tau}}$
via \rref{equiv-refl} for instance,
$\type{\compile{\Phi}, \compile{\Gamma}}{\yT}{\compile{\tau}}$
would be required,
but this can't be constructed even from
$\type{\Phi; \Gamma}{y}{\tau}$
as it's not a premise and therefore the mutual type preservation induction hypothesis can't be applied.
Still, I use untyped conversion to avoid any other potential complications with the mutual induction.
\fi

On the other hand, induction isn't done on the derivations of the target,
but since equality reflection is needed for translation-specific reasons,
\CICE uses typed equivalence instead to avoid the inconsistency and loss of subject equivalence
arising from reflecting propositional equality into transitive, untyped conversion,
as detailed in \cref{sec:target}.

Due to the incongruity between untyped conversion in the source and typed equivalence in the target,
the na\"ive proof attempts at preservation using only the relevant source derivation
and well-typedness of the source terms would be missing crucial typing information
to construct the target derivations, especially for equivalence.
This is why, in all of the preservation lemmas, well-typedness of the translated terms
are also required as premises, essentially replacing what would've been mutual or circular appeals
to type preservation with just the right amount of typing information.

Quite unexpectedly, requiring well-typedness of translated terms
also has an effect on whether conversion in the source is declarative or algorithmic.
If conversion were declarative like \CICE's equivalence, with no reduction rules or their closures,
then transitivity of subtyping would need to be an explicit rule rather than a theorem.
%
\begin{mathpar}
\inferrule{
  \subtype{\Phi; \Gamma}{\tau_1}{\tau_2} \\
  \subtype{\Phi; \Gamma}{\tau_2}{\tau_3}
}{
  \subtype{\Phi; \Gamma}{\tau_1}{\tau_3}
}
\end{mathpar}
%
Recall that preservation of subtyping states that if $\subtype{\Phi; \Gamma}{\tau_1}{\tau_3}$ holds
and $\tau_i, \compile{\tau_i}$ for $i = 1, 2$ are well typed,
then $\subtype{\compile{\Phi}, \compile{\Gamma}}{\compile{\tau_1}}{\compile{\tau_3}}$ holds.
To apply the induction hypotheses in the above transitivity case,
we would need well-typedness of all of $\compile{\tau_1}, \compile{\tau_2}, \compile{\tau_3}$;
for the first and last, they're provided as premises.
But where would we derive the well-typedness of $\compile{\tau_2}$?
There's no ``subject subtyping'' as there is for subject reduction, and indeed,
$\subtype{\mt; \mt}{\Type{1}}{\App{(\fix{f}{\alpha}{\N{\alpha}}{\Type{2}})}{\sss{\circ}}}$
holds while the right-hand side, which is convertible to $\Type{2}$, isn't even well typed.

So simply by deciding on a syntactic model into an extensional type theory,
definitional equality in the source must be untyped and algorithmic,
while in the target it must be typed,
lest we create headaches for ourselves with these complex yet avoidable issues.

These consequences have further effects on the design of the source syntax,
particularly concerning type annotations, if we also take into account
the other required metatheoretical properties.
Proving subject reduction in the case of $\delta$-reduction requires that
definitions in the environment have type annotations;
otherwise, even if $\Gamma = (\define*{x}{e}), (\annot{x}{\tau})$ were well formed,
we can't guarantee that $x$ reduces to $e$ of the \emph{same} type $\tau$,
only that $e$ has \emph{some} type.
Type-annotated definitions in turn force locally-named expressions
in $\kw{let}$ expressions to have annotations as well.
In the congruence rule that reduces the body of a $\kw{let}$ expression,
the named expression needs to be added as a definition to the environment,
but since reduction is untyped, its type can't be derived:
it must be provided by the $\kw{let}$ expression itself.

Although not directly related to the type preservation proofs,
proving confluence requires that the notion of $\rhd^*$ be
exactly the reflexive, transitive closure of $\rhd$,
so the congruence rules need to be a part of $\rhd$ and not of $\rhd^*$.

Some of these constraints are not so serious:
$\kw{let}$ expressions without type annotations, for instance,
can be easily elaborated into a core calculus with annotations.
Other constraints require more work to handle:
although a variant of \lang with typed equivalence would instinctively be equivalent
to \lang without, proving that nothing has been broken by the introduction of typed equivalence
requires yet another syntactic model, which would have the same mutual induction issues.
In other words, a syntactic model constrains us to a particular presentation of the type theory
and its judgement rules, and changing the presentation (\eg for implementation in a type checker)
requires either more proof work or a certain amount of trust in the correctness of the changes.

\section{Future Directions}

There is still a long way to go towards a sized dependent type system
that is expressive, consistent, and useable.
We've seen from \cref{sec:examples} that working without an infinite size
or full inductives is verbose at best, in the case of $\msort$ and $\qsort$,
and impossible at worse, in the case of $\const{\omega}$,
while attempts at including them either involve inconsistency, undecidability, or noncanonicity.
Alternate approaches need to be investigated to circumvent these problems.

While the issue with the universe levels of inductive types appears to be cosmetic
and not affect any important significant metatheoretical properties,
it might be a mere symptom of a larger issue with how sizes are modelled,
especially since prior sized type systems shown to be consistent
haven't required any similar restrictions.
One possibility is to take inspiration from Agda and
make $\SizeT$ live in a universe $\SizeUnivT$ independent of $\TypeT{}$,
but the consistency of arbitrarily adding a new universe is questionable,
especially when $\SizeUnivT$ needs to be slightly impredicative:
$\arrT*{\TypeT{}}{\SizeT}$ would remain in $\SizeUnivT$
(as would be the case for $\limT$)
and $\funtypeT{\alpha}{\SizeT}{\N{\alpha}}$ would remain in $\TypeT{0}$
(as would be the case for $\zeroT$).

The main barrier to a syntactic model\index{syntactic model} of \lang with any coinductive types
is the lack of an established target type theory with coinductive types
with nice properties.
Whereas pCIC\index{Calculus of Inductive Constructions!Predicative \textasciitilde}
and pCuIC\index{Predicative Calculus of Cumulative Inductive Constructions} lack them,
MetaCoq\index{MetaCoq} mechanizes Coq-style coinductive types,
but necessarily cannot prove its own consistency.
Meanwhile, older CICs with coinductive types and cofixpoints guarded by constructors\index{guardedness}
(\eg \citet{guard}) have issues with subject reduction~\citep{coind-SR}\index{subject reduction},
which is a necessary property for proving type preservation\index{type preservation} in \cref{ch:proofs}.
Another potential issue is the translation of cofixpoints into applications of
a well-founded induction principle, which is suspicious and also requires further investigation.

Finally, \lang is missing some important but comparatively simple features
from the perspective of the syntactic model, namely inductive types in general.
They can be added directly to \lang as a generalization of the existing inductives,
and I conjecture that the type preservation proofs would be a straightforward extension.
Alternatively, since there already are well-founded trees,
\lang could instead be augmented with dependent pairs and an equality type,
both of which I also conjecture to be straightforward;
then mutual inductives, indexed inductives \citep{whynotW}, some nested inductives \citep{barras},
and even some inductive--inductive types \citep{ind-ind}
can be encoded, along with their induction principles, using W types and propositional equality.

\hfill

In terms of metatheory, \lang is missing proof of two desirable properties:
strong normalization and decidability of type checking.
Because \nameref{lem:pres-red} only preserves reduction up to equivalence in \CICE,
not reduction, normalization doesn't hold immediately from the translation.
In particular, the proof of \nameref{lem:pres-red} uses equality reflection
to obtain an equivalence between two proofs of accessibility\index{accessibility predicate} of a size,
and \citet{SProp} show that this equivalence can lead to nonnormalization in
particular inconsistent environments,
as is the case for $\tg{false}$.

Even so, I conjecture that translation of a \lang term will never lead to
a \CICE term with a subterm in an appropriate inconsistent environment that leads to nonnormalization,
because the translation will never yield an assumption of the form $\sT \szltT \sT$.
By inspection of the translation, the only fitting subsizing relation possible is of the form $\alphaT \szltT \alphaT$,
and the only possible sources $\Funtype<{\alpha}{\alpha}{\tau}$, $\Fun<{\alpha}{\alpha}{e}$ are ill-scoped.
Since fixpoints only reduce when applied to sizes that have a subsize
and we can't obtain infinitely decreasing chains of subsizes,
they can't unfold endlessly and must stop eventually.

Decidability of type checking, meanwhile, rests not only on strong normalization,
but also on decidability of subsizing, \ie deciding whether $\bound{r}{s}$ holds.
The trickiest rule is transitivity of subsizing,
but I conjecture that subsizing, too, is decidable,
as the size environment only contains a finite number of bounded size variables,
and sizes can only have a finite number of successor operators applied.
Moreover, Agda has transitive subsizing, and so far hasn't had issues with its decidability.

\hfill

As for implementation, the consistency of \lang shows that sized types for inductives in Agda
are likely to be consistent were the infinite size\index{infinite size} removed.
This immediately poses a significant problem to Agda's standard library,
as 20 of the 33 files that use sized types in version 1.7.1 of the standard library use the infinite size.
Furthermore, 30 of those files deal with coinductives rather than inductives,
and it remains to be seen whether \lang with coinductives really is consistent as well.
The addition of the $\const{ac}$ axiom to recover some of the expressivity of the infinite size
isn't ideal for a proof assistant either, since it would block computation.

\section{Conclusion}

In this thesis, I introduced \lang, a sized dependent type theory
with higher-rank size quantification and bounded size quantification,
but without an infinite size that is strictly greater than itself,
along with sized naturals and well-founded trees.
I gave examples of programming with sized inductives to write recursive programs
that would have otherwise not passed the usual syntactic guard checks,
as well as limitations of programming without the infinite size.
I then reduced the consistency of \lang to that of \CICE,
an extensional dependent type theory, by translating \lang terms to \CICE terms
and proving that the translation is type preserving.
Finally, I discussed the tradeoffs in the design of \lang for this syntactic model to work,
namely the lack of an infinite size and raising the universe levels of the inductives,
as well as some potential extensions and future work.


\documentclass[12pt]{amsart}
\usepackage[margin=0.5in]{geometry}
	% see geometry.pdf on how to lay out the page. There's lots.
\usepackage{bsymb}
\usepackage{../unitb}
\usepackage{calculational}
\usepackage{ulem}
\usepackage{hyperref}
\normalem
\geometry{a4paper} % or letter or a5paper or ... etc
% \geometry{landscape} % rotated page geometry

% See the ``Article customise'' template for some common
% customisations

\title{}
\author{}
\date{} % delete this line to display the current date

%%% BEGIN DOCUMENT
\setcounter{tocdepth}{4}
\begin{document}

\maketitle
\tableofcontents

\input{main8/machine_m1}
\input{main8/machine_m2}
\newcommand{\stmt}[1]{ $#1$ }
% \newcommand{\comment}[2]{
% 	% \begin{tabular}{|l|l|}
% 	% 	\hline
% 		\begin{description}
% 		\item[{#1}] ~ #2
% 		\end{description}
% 	% 	\hline
% 	% \end{tabular}
% 	}
\newcommand{\commentbox}[1]{
	\begin{block} \item \small{ #1 } \end{block} }
\newcommand{\G}{\text{Val}}
\newcommand{\Req}{\text{Req}}
% \renewcommand{\H}{\text{H}}

\section{Initial model --- Requests}
\input{main8/machine_m0}
\begin{machine}{m0}
	\with{functions}
	\with{sets}
	\newset{\G} \newset{\Req}
	\newevent{req:push:left}{request\_push\_left}
	\newevent{req:push:right}{request\_push\_right}
	\newevent{req:pop:left}{request\_pop\_left}
	\newevent{req:pop:right}{request\_pop\_right}
	\newevent{resp:push:left}{respond\_push\_left}
	\newevent{resp:push:right}{respond\_push\_right}
	\newevent{resp:pop:left}{respond\_pop\_left}
	\newevent{resp:pop:right}{respond\_pop\_right}
	\[\variable{ppL,ppR : \set[\Req] } \]
	\[\variable{psL,psR : \Req \pfun \G }\]
	\[ \dummy{r : \Req} \]
	\[ \dummy{X : \G} \]
    \[ \param{req:push:left}{r : \Req} \]
    \[ \param{req:push:right}{r : \Req} \]
    \[ \param{req:push:left}{x : \G} \]
    \[ \param{req:push:right}{x : \G} \]
    \[ \param{req:pop:left}{r : \Req} \]
    \[ \param{req:pop:right}{r : \Req} \]
\subsection{Issuing requests}

\begin{align}
	&\evguard{req:push:left}{m0:grd0}{ \neg r \in \dom.psL } \\
	&\evbcmeq{req:push:left}{m0:act0}{psL}{ psL \1| r \fun x } \\
	&\evguard{req:push:right}{m0:grd0}{ \neg r \in \dom.psR } \\
	&\evbcmeq{req:push:right}{m0:act0}{psR}{ psR \1| r \fun x } \\
	&\evguard{req:pop:left}{m0:grd0}{ \neg r \in ppL } \\
	&\evbcmeq{req:pop:left}{m0:act0}{ppL}{ ppL \1\bunion \{r\} } \\
	&\evguard{req:pop:right}{m0:grd0}{ \neg r \in ppR } \\
	&\evbcmeq{req:pop:right}{m0:act0}{ppL}{ ppL \1\bunion \{r\} }
\end{align}

\subsection{Requirements}

\begin{align}
	\progress{m0:p0}
		{r \in \dom.psL }
		{ \neg r \in \dom.psL } \\
	\progress{m0:p1}
		{r \in \dom.psR }
		{ \neg r \in \dom.psR } \\
	\progress{m0:p2}
		{r \in ppL }
		{ \neg r \in ppL } \\
	\progress{m0:p3}
		{r \in ppR }
		{ \neg r \in ppR } \\
	\safety{m0:s0}
		{ psL.r = X }
		{ \neg r \in \dom.psL } \\
	\safety{m0:s1}
		{ psR.r = X }
		{ \neg r \in \dom.psR }
\end{align}

\subsection{Addressing the requirements}
\[ \indices{resp:pop:right}{r : \Req} \]
\[ \indices{resp:pop:left}{r : \Req} \]
\[ \indices{resp:push:right}{r : \Req} \]
\[ \indices{resp:push:left}{r : \Req} \]
\begin{align}
	\refine{m0:p0}{ensure}{resp:push:left}{ \index{r}{r' = r} }
	\cschedule{resp:push:left}{m0:sch0}{ r \in \dom.psL } \\
	\evbcmeq{resp:push:left}{m0:act0}{psL}{ \{r\} \domsub psL }
\end{align}
% \removecoarse{resp:push:left}{default}
\begin{align}
	\refine{m0:p2}{ensure}{resp:pop:left}{ \index{r}{r' = r} }
	\cschedule{resp:pop:left}{m0:sch0}{ r \in ppL } \\
	\evbcmeq{resp:pop:left}{m0:act0}{ppL}{ ppL \setminus \{ r \} }
\end{align}
% \removecoarse{resp:pop:left}{default}
\begin{align}
	\refine{m0:p1}{ensure}{resp:push:right}{ \index{r}{r' = r} }
	\cschedule{resp:push:right}{m0:sch0}{ r \in \dom.psR } \\
	\evbcmeq{resp:push:right}{m0:act0}{psR}{ \{r\} \domsub psR }
\end{align}
% \removecoarse{resp:push:right}{default}
\begin{align}
	\refine{m0:p3}{ensure}{resp:pop:right}{ \index{r}{r' = r} }
	\cschedule{resp:pop:right}{m0:sch0}{ r \in ppR } \\
	\evbcmeq{resp:pop:right}{m0:act0}{ppR}{ ppR \setminus \{ r \} }
\end{align}
% \removecoarse{resp:pop:right}{default}
\end{machine}
\section{First Refinement --- Sequence of Values}
\input{main8/machine_m1}
\begin{machine}{m1}
	\refines{m0}
	\with{intervals}
\splitevent{resp:pop:right}{resp:pop:right:empty,resp:pop:right}
\splitevent{resp:pop:left}{resp:pop:left:empty,resp:pop:left}
	\[ \variable{p,q : \Int} \]
	\[ \variable{qe : \Int \pfun \G} \]
	\[ \variable{emp : \Bool } \]
	\[ \variable{ res : \G } \]
\begin{align}
	\invariant{m1:inv0}{ qe \in \intervalR{p}{q} \tfun \G } \\
	\invariant{m1:inv1}{ p \le q } \\
	\initialization{m1:init0}{ qe = \emptyfun } \\
	\initialization{m1:init1}{ p = 0 \land q = 0 } \\
	\evbcmeq{resp:push:right}{m1:act0}{q}{q+1} \\
	\evguard{resp:push:right}{m1:grd0}{ r \in \dom.psR } \\
	\evbcmeq{resp:push:right}{m1:act1}{qe}{ qe \1| q \fun psR.r } \\
	\evbcmeq{resp:pop:right}{m1:act0}{q}{q-1} \\
	\evguard{resp:pop:right}{m1:grd0}{\neg p = q} \\
	\fschedule{resp:pop:right}{m1:sch0}{\neg p = q} \\
	\evbcmeq{resp:pop:right}{m1:act1}{qe}{ \{ q\0-1 \} \domsub qe } \\
	\evbcmeq{resp:pop:right}{m1:act2}{emp}{ \false } \\
	\evbcmeq{resp:pop:right}{m1:act3}{res}{ qe.(q\0-1) } \\
	\fschedule{resp:pop:right:empty}{m1:sch0}{ p = q } \\
	\evguard{resp:pop:right:empty}{m1:grd0}{ p = q } \\
	\evbcmeq{resp:pop:right:empty}{m1:act2}{emp}{ \true } \\
	\evbcmeq{resp:push:left}{m1:act0}{p}{p-1} \\
	\evguard{resp:push:left}{m1:grd0}{ r \in \dom.psL } \\
	\evbcmeq{resp:push:left}{m1:act1}{qe}{qe \1| p\0-1 \fun psL.r} \\
	\evbcmeq{resp:pop:left}{m1:act0}{p}{p+1} \\
	\evguard{resp:pop:left}{m1:grd0}{\neg p = q} \\
	\fschedule{resp:pop:left}{m1:sch0}{\neg p = q} \\
	\evbcmeq{resp:pop:left}{m1:act1}{qe}{ \{ p \} \domsub qe } \\
	\evbcmeq{resp:pop:left}{m1:act2}{emp}{ \false } \\
	\evbcmeq{resp:pop:left}{m1:act3}{res}{ qe.p } \\
	\fschedule{resp:pop:left:empty}{m1:sch0}{ p = q } \\
	\evguard{resp:pop:left:empty}{m1:grd0}{ p = q } \\
	\evbcmeq{resp:pop:left:empty}{m1:act2}{emp}{ \true }
\end{align}
\end{machine}
\begin{machine}{m2}
	\refines{m1}
\end{machine}
\end{document}


%\section{SNoW for MWMR setting}\label{mwmr}
Here present  algorithm  $B$, which satisfies  SNW and "one-version" properties, in MWMR setting where a \rot{} must consist of one version of the data but, possibly, multiple communication trips between the reader and the servers.% We denote the type of object  that satisfies the SNoW properties by $\tilde{\mathcal{O}}_T$.
%Note that $B$ can also tolerate crash failure of writers and readers.
In B, the steps for the writers are shown in Pseudocode~\ref{fig:algo_bc} and for readers and the servers  are presented in Pseudocode~\ref{fig:algo_b}.
We assume  a set of writers $\mathcal{W}$,  a set of readers $\mathcal{R}$ and a set of $k \geq 1$ servers,  $\mathcal{S}$, with ids $s_1, s_2\cdots s_k$ that stores the objects $o_1, o_2, \cdots, o_k$, respectively.  We define  key ${\kappa}$ is defined as a pair $(z, w)$,
where $z \in \mathbb{N}$ and $w \in \mathcal{W}$ the  id of a writer. We use $\mathcal{K}$ to denote the set of all possible keys.
In $B$, the keys are used to uniquely identify each transaction. Also, with each transaction we associate a tag $t \in \mathbb{N}$.
%We assume writers can send message to the reader, i.e., we allow client-to-client messages.
% We assume that each process has a unique id. We assume that each server $s$ stores object $o_s$, due to sharding.  For the sake of simplicity, we assume that the \wots{} issued by a writer are of the form: \emph{ write value $v_1$ to object $o_1$, $v_2$ to $o_2$, and so on}. In other words, we assume that such a  transaction consists of the set of operations $\{ \writeop{o_1}{v^{(1)}}, \writeop{o_2}{v^{(2)}}\cdots \writeop{o_k}{v^{(k)}}\} $, which we denote by $write(v_1, v_2, \cdots, v_k)$.  \wots{} where only a subset of  the objects are updates will be discussed later. We also assume that  the \rots{} are of the form  $\{ \readop{o_1}, \readop{o_2}\cdots \readop{o_k}\}$ consisting of $k$ reads to $k$ distinct objects.

In  $B$, we designate one of the servers as coordinator, denote as $s^*$,
 for the transactions. The $s^*$  maintains the order of the \wots{} and the objects that are updated during the \wot{} in the variable $List$.  %Note that in a system, where there are many objects
%different objects may be use different servers  as coordinators based on some load-balancing rule.

\textit{\textbf{State variables:}} Each of the writers and servers maintain a set of state variables as follows: $(i)$ At  any  \emph{writer $w$}, there is  a counter $z$ to keep track of the
 number of \wot{}  the writer has  invoked, initially $0$. $(ii)$ At any  \emph{server}, $s_i$,
 for $i \in [k]$, there is  a set variable $Vals$
 with elements
 that are  key-value pairs $({\kappa}, v_i) \in \mathcal{K} \times \mathcal{V}_i$. Initially,
  $Vals= \{ ({\kappa}^0, v_i^0)\}$. %This ensures that each \wot{} generates a unique key.
A server also contains an
 ordered list variable $List$  of elements  as $({\kappa}, (b_1, \cdots, b_k))$,  where
 ${\kappa}  \in \mathcal{K}$  and
 $(b_1, \cdots b_k) \in  \{0, 1\}^k$. Initially,
 $List= [ ({\kappa}^0, (1, \cdots 1) ]$, where ${\kappa}^0  \equiv (0, w_0)$,
 where $w_0$ is any
  place holder identifier string for writer id. The elements in $List$ can be identified with an index, e.g.,
  $List[0] =({\kappa}^0, (1, \cdots, 1))$.  Essentially, a $(k+1)$-tuple  $(\kappa, (b_1, \cdots, b_k))$ in $List$ corresponds to a \wot{} and
   identifies the set of objects that are updated during the \wot{}, i.e., if $b_i=1$ then object
   $o_i$ was updated  during  the  \wot{}, otherwise $b_i=0$.
			%labeled with phase names, viz., {\readGetTag}, {\readValueTag}, {\readCompleteTag} and {\writeGetTag}. The server to server messages are labeled as {\readDisperseTag}. Also, in some phases of {\SODA},  the message-disperse primitives {\mdmetaprim} and {\mdvalueprim} are used  as services.

\textit{\textbf{Writer steps:}} A \wot{} updates
			a  list of $p$ objects $o_{i_1}, o_{i_2}, \cdots o_{i_p}$  with values
			 $v_{i_1}, v_{i_2}, \cdots v_{i_p}$, respectively, is invoked at $w$ via the procedure
			$\Writetr{ (o_{i_1}, v_{i_1}), \cdots, (o_{i_p}, v_{i_p}) }$.
We use the notations:  $I \triangleq \{i_1, i_2, \cdots, i_p\}$  and $S_I\triangleq \{s_{i_1}, s_{i_2}, \cdots, s_{i_p}\}$.
This procedure  consists of two phases: {\writeValue} and {\updateCoord}.
%We denote the set of servers involved   in the \wot{}  by  $S_I=\{s_{i_1}, s_{i_2}, \cdots, s_{i_p}\}$.
During the {\writeValue} phase,  $w$ creates a new key ${\kappa}$ as
 $ {\kappa}  \equiv (z + 1, w)$, where $w$ identifies the writer; and also increments the local counter $z$ by one.  Then $w$ sends $(${\writeValueTag}$, ({\kappa}, v_{i}))$ to each server in $S_I$, and awaits {\ackTag}
from all servers in $S_I$.
After receiving {\ackTag} from all servers in $S_I$,  $w$
initiates the {\updateCoord} phase where it sends
(\updateCoordTag, $({\kappa}, (b_{1}, \cdots b_{k})$) to $s^*$, where for any $i \in [k]$,  $b_i=1$ if $s_i \in S_I$,
otherwise $b_i=0$,   and completes then \wot{} after it receive a   ({\ackTag}, $t_w$) from $s^*$.
%	  After receiving message  ({\ackTag}, $t_w$),  $w$ completes the \wot{}.

%At $s^*$, upon receiving  (\updateCoordTag, $({\kappa}, (b_{1}, \cdots, b_{k})$) from $w$ appends
%			 $({\kappa}, (b_{1}, \cdots, b_{k}))$ to its  $List$,  and responds with
%			 {\ackTag} and $t_{w}$ (set to be the number of elements in the local list $List$)  to $w$.
%			 The order of the  elements in  $List$ corresponds to  the order
%the \wots{}, the order of the incoming  {\updateCoordTag} updates,  as seen by $s^*$.
%			  After receiving an ({\ackTag}, $t_w$),  $w$ completes the \wot{}.

\textit{\textbf{Reader steps:}}
We use the same notations for $I$ and $S_I$ as above but the indices can vary across  transactions.
The procedure  \Readtr{$ o_{i_1},  o_{i_2}, \cdots, o_{i_p}$} can be
initiated by  some reader  $r$,   as a \rot{}, intending to read the values of
subset $o_{i_1},  o_{i_2}, \cdots, o_{i_p}$ of the objects. The procedure
consists of two consecutively executed phases of communication rounds
between the $r$ and the  servers, viz.,  {\getTagArray} and {\readValue}.
%
During  the  phase {\getTagArray},  $r$ sends $s^*$ the message  {\getTagArrayTag}
 requesting the  list of the latest added keys for each object.
 Once $r$ receives a list of tags, such as, $(t_r, ({\kappa}_1, {\kappa}_2, \cdots,  {\kappa}_k))$ from $s^*$   the phase completes.
%
%
In the subsequence phase, {\readValue},   $r$ requests each server $s_i$ in $S_I$ by sending the message
$(\text{\readValueTag}, \kappa_i)$.
% Then upon receiving such a request, any server $s_i$ responds with  $(${\readValueTag}$, {\kappa}^{s_i})$, i.e., one version of  $o_i$ corresponding to the key $t_i$ to $r$, stored in its $Vals$.
%
%During  phase {\readValue}, 	 the reader sends to each of the servers in
%$\mathcal{S}$, say $s_i$ the key ${\kappa}^{s_i}$ corresponding
%			 to $(k+1)$-tuple of $List$ with the latest  index $j^*$ such that $b_i =1$ such that
%$i \in I$, where $I \triangleq  \{{i_1},  {i_2}, \cdots, {i_p}\}$,  requesting the corresponding value.
%Any server $s_i$ upon receiving
%such a message with $(${\readValueTag}$, {\kappa}^{s_i})$ responds with $v$ such that $({\kappa}^{s_i}, v_i)$ is in its variable $Vals$.
After  receiving the values $v_{i_1}$, $v_{i_2}, \cdots v_{i_p}$ from the servers in $\mathcal{S_I}$,
 $r$ completes the transaction  by
 returning the tuple of values $(v_{i_1}, \cdots v_{i_p})$.
 % and set the tag $t_r$ as  the latest index in $List$ corresponding to a \wot{} that updated  one of the object in the \rot{}, i.e., $\max_{1 \leq j \leq |List|} \{ j : List[j].b_i = 1 \wedge i \in I\}$.

\textit{\textbf{Server steps:}}
When a server $s_i$ receives a message of type $(${\writeValueTag}$, ({\kappa}, v_{i}))$ from a writer $w$ then
%to each server in $S_I$, and awaits {\ackTag}
%from all servers in $S_I$.
it  adds $({\kappa}, v_i)$ to its set variable
$Vals$ and sends {\ackTag} back to $w$.

If the coordinator $s^*$ receives  (\updateCoordTag, $({\kappa}, (b_{1}, \cdots, b_{k})$) from writer $w$, then it appends
			 $({\kappa}, (b_{1}, \cdots, b_{k}))$ to its  $List$,  and responds with
			 {\ackTag} and $t_{w}$ (set to be the number of elements in the local list $List$)  to $w$.
			 The order of the  elements in  $List$ corresponds to  the order
the \wots{}, the order of the incoming  {\updateCoordTag} updates,  as seen by $s^*$.

When $s^*$  receives  the message  {\getTagArrayTag} from $r$  it responds with
$(\kappa_1, \cdots, \kappa_k)$ such that for each $i \in [k]$, $\kappa_i$ is the key  part of the $(k+1)$-tuple that was modified
last, i.e., 	${\kappa}_i = List[j^*].{\kappa}$ such that 	 $j^* \triangleq\max \{ j : List[j].b_i =1 \}$, and
$t_r$, $t_r \triangleq \max_{1 \leq j \leq |List|} \{ j : List[j].b_i = 1 \wedge i \in I\}$.
%
  	If any server $s_i$ receives a message  $(${\readValueTag}$, {\kappa})$ from a reader $r$ then it responds to $r$ with
   the value $v_i$ corresponding to key with value  $\kappa$ in  $Vals$.

The following result states that algorithm $B$ respects SNW and "one-round" properties.
% and the proof is omitted for now since it is very straightforward. Note that the liveness property of \rot{} and \wot{}  transactions are a part of the SNOW properties.
%Consider any failure-free and fair execution of algorithm $B$.
%For the purpose of proving the $S$ property, for every transaction transaction  $\phi$ in an execution of $B$ we associate a tag $tag(\phi)$ as described below.
% the variable $t_r$ in a reader and $t_w$ in
%a writer are used to associate a tag as described below.
% $ \triangleq \max_{1 \leq j \leq |List|} \{ j : List[j].b_i = 1 \wedge i \in I\}$, which is presented as a comment in the pseudo-code for $A$.
%If $\phi$ is a \wot{} (\rot{}) then  $tag(\phi)$ is the value of the variable $t_w$ ($t_r$) immediately before the
%operation completes.

\begin{theorem} Any well-formed  and fair execution of algorithm $B$  satisfies the SNW and "one-round"  properties. %Algorithm $B$ also tolerates any client crash failures.
\end{theorem}

%	\begin{theorem} Any well-formed  and fair execution of algorithm $B$ is an implementation of  an object of type $\tilde{\mathcal{O}}_T$ in the MWMR setting, 	with no client-to-client communication,  comprising of objects $o_1, o_2, \cdots o_k$ stored in servers $s_1, s_2, \cdots, s_k$, respectively; and it satisfies the SNoW  properties. %Algorithm $B$ also tolerates any client crash failures.\end{theorem}

\remove{
\begin{proof} Below we show that algorithm $B$ satisfies the  SNoW properties.

	\noindent{\emph{\underline{S property:}}}
	Let $\beta$ be any fair execution  of  $B$ and
 suppose all clients in $\beta$ behave in a well-formed
manner. Suppose $\beta$ contains no incomplete transactions and let  $\Pi$ be the set of transactions in $\beta$.  We define an irreflexive partial ordering ($\prec$) in $\Pi$ as follows:  if $\phi$ and $\pi$ are any two distinct transactions in $\Pi$ then we say
	$\phi \prec \pi$ if either $(i)$ $tag(\phi) < tag(\pi)$ or $(ii)$ $tag(\phi) = tag(\pi)$ and $\phi$ is a \wot{} and $\pi$ is a \rot{}. Below we prove the $S$  property of $B$ by showing that  properties $P1$, $P2$, $P3$ and $P4$ of Lemma~\ref{lem:equivalence} hold for $\beta$.

	\emph{P1:}   Clearly, from an inspection of the algorithm,
	 $tag(\pi) \in \mathbb{N}$. From inspection of the algorithm, each \wot{} increases the size of
	 $List$, and the value of the tags are  defined by the size of $List$. Therefore, there can be at
	 most a finite number of \wots{} such that can precede $\pi$ (w.r.t. $\prec$) in $\beta$.
	  On the other hand, if $\pi$ is a \rot{} then since all \rot{}s are invoked by readers  in a well-formed manner,  and there are only finite number of readers
	therefore, there cannot be an infinite number of \rot{}s such that they all
	precede $\pi$ (w.r.t $\prec$).

	\emph{P2:}  Suppose $\phi$ and $ \pi$ are any two transactions in $\Pi$, such that, $\pi$ begins after $\phi$ completes. Then we show that we have  we cannot have $\pi \prec \phi$. Now, we consider four cases, depending on whether $\phi$ and $\pi$ are \rot{}s or \wots{}.
	\begin{enumerate}
	    \item [$(a)$] $\pi$ and $\phi$ are \wots{} invoked by writers $w_{\pi}$ and $w_{\phi}$, respectively. Since the size of $List$, in $s^*$ grows monotonically due to each \wot{}  hence  $w_{\pi}$ receives the  tag  from $s^*$ at least as high as $tag(\phi)$, so $\pi\not \prec \phi$.
	      %
	       \item [$(b)$] $\pi$ is a \rot{}, $\phi$ is a \wot{} invoked by reader  $r_{\pi}$ and writer $w_{\phi}$, respectively.
	        Since the size of $List$, in $s^*$,  grows monotonically,  because  $r_{\pi}$  invokes $\pi$ after $\phi$ completes hence $tag(\pi)$ is at least as high as $tag(\phi)$, so $\pi\not \prec \phi$.
	      %
	        \item[$(c)$]$\pi$ and $\phi$ are both \rot{}s  invoked by readers $r_{\pi}$ and $r_{\phi}$, respectively.
	           Since the size of $List$, in $s^*$, grows monotonically,  because   $w_{\pi}$ invokes $\pi$ after $\phi$ completes hence $tag(\pi)$ is at least as high as $tag(\phi)$, so $\pi\not \prec \phi$.
	        %
	         \item [$(d)$] $\pi$ is a \wot{}, $\phi$ is a \rot{}  invoked by writer $w_{\pi}$ and reader $r_{\phi}$, respectively.
	         This case is simple because new values are added to $List$, in $s^*$,  only  by writers, and $tag(\pi)$  has to be larger than the tag of $\phi$ and hence   $\pi\not \prec \phi$.
	\end{enumerate}

	\emph{P3:} This is from  the fact that any \wot{} always creates a unique tag and all tags are totally ordered since they all belong to $\mathbb{N}$

		\emph{P4:} Consider a \rot{} $\rho$ as $READ(o_{i_1}, o_{i_2}, \cdots, o_{i_q})$, in $\beta$.
Let the returned value from $\rho$ be $\mathbf{v} \equiv $$(v_{i_1}, v_{i_2}, \cdots, v_{i_q})$ such that
$1 \leq {i_1} <  {i_2} <  \cdots <  {i_q} \leq k$, where value  $v_{i_j}$ corresponds to $o_{i_j}$.
	Suppose $tag(\rho) \in \mathbb{N}$ was created during some \wot{}, say $\phi$, i.e., $\phi$ is the \wot{} that
	added the elements in index $(tag(\rho)-1)$ of $List$ at the coordinator $s^*$. Note that element in index $0$ contains the initial value.
	%because \rots{} do not generate new tags as they do not add any new item to the $Vals$ of any server.
	 Now we consider two cases:

	\emph{Case $tag(\rho) = 1$.} We  know that it corresponds the initial default value $v_i^0$ at each sub-object $o_i$, and this equates to $\rho$ returning the default initial value for each sub-object.
	 %
	% Therefore, $tag(\rho) = tag(\phi)$.

	 \emph{Case $tag(\rho) > 1$.} Then we argue that there exists no \wot{}, say $\pi$, that updated object $o_{i_j}$,   in $\beta$, such that,  $\pi \neq \phi$ and $\rho$ returns values written by $\pi$ and $\phi \prec \pi \prec \rho$. Suppose we assume the 	contrary, which means $tag(\phi) < tag(\pi) < tag(\rho)$. The latter implies $tag(\phi)  = tag(\pi)$ which is not possible because
	this contradicts the fact that for any two distinct \wots{} $tag(\phi) \neq tag(\pi)$  in any execution of   $B$.

	\noindent{\emph{\underline{N, o and W properties:}}}  Evident from an inspection of the algorithm.
	% for the  response steps  of the servers to the reader.
	\end{proof}
}


% -*- root: ../main.tex -*-
\chapter{Design\label{chap:design}}

\paragraph{Abstract}

In this chapter we define the way that formal verification can be achieved, for which first we define some notation and definitions.
%
After some generalities about formal verification, we define more concrete aspects of the formal verification we aim to achieve, such us the linked-list theory used.
%
%
%
\section{Program correctness}
%
We are finally ready to apply this concepts to a real word problem. In this \thisworkm we apply those concepts to prove some properties of programs.
%
The remaining task is to define the framework and the conventions we use to formally prove  properties of programs.

The way we approach to assess correctness is by proving properties.
%
There are \concept{liveness}, \concept{safety} and \concept{functional} properties.
%
Safety properties refer, informally, to “bad things never happens”. Proving \textit{ variable x is never 0 } is a safety property.
%
Proving valid this property can assure that a division by zero error will never occur.
%
Whether a program finishes or not is a liveness property, and producing an output for a concrete input is a functional property.

These properties are written in some logic.
%
Liveness properties require the use of temporal logic but we restrict ourselves to use safety properties so no machinery for temporal properties is needed.
%
As the properties are expressed formally in \gls{FOL}, it is necessary to define a formal representation of a program.

\label{def:SPL}
\input{src/spl}

\subsection{Partial correctness (Safety)}

A function (or the whole program) is \textbf{partially correct} if whenever the function's precondition is satisfied on entry, its postcondition is satisfied when the function returns (if it ever does).
%
We present the \concept{inductive assertion method} for proving partial correctness.

Let $\varphi$ be the \gls{FOL} property to study.
%
The procedure is the following:
%
First each function is reduced to a finite set of \gls{FOL} formulae called \concept[Verification condition]{\gls{VC}}.
%
This reduction is done with the basic reducing cases we studied in \ref{def:SPL}.
%
The goal is to prove that $\varphi$ is valid in every state of the execution.
%
\textbf{Induction} is the methodology used.
%
First, we assert $\varphi$ is valid before the program starts (induction base).
%
Then, we assume $\varphi$ in the precondition and prove $\varphi'$ valid (induction step) for every possible transition.

This method is not complex to understand but it requires a lot of work even for simple programs.
%
We illustrate this method with an example in \ref{app:exampleFactorial}.

\vspace{-0.3cm}
\section{Parametrized systems}

The correctness of a program executed by just one thread it is an easier problem because the program runs sequentiality.
%
Multiple threads executing the same program is a different and more difficult problem to solve.
%
An unbounded number of threads executing is another important and difficult extension.
%
If the number of threads is bounded, one could unroll the formula for all the threads in the problem.
%
As this is the usual scenario, we focus the unbounded case.

We are going to study those cases.
%
To do so, we need to parametrize the program executed by multiple threads.
%
Typically we use  $i$,$j$,$k_0$,$k_i$ for threads identifiers.

\vspace{-0.3cm}
\subsubsection{Arbitrary number of threads}

For example, the web servers may not have a bound of the number of clients they can accept.
%
Can we prove correctness when an unbounded number of processes are using the same global variables?

A recent research \citeapos{paperParametrizedInvariants} has proven a very important result.
%
We will present this result new as it is fundamental for this work.
%
We will not formally prove any of the results proven in \citep{paperParametrizedInvariants}.

Before we enunciate the theorem, we need some previous concepts.
%
We need to extend the concept of support to parametrized formulas.

\begin{defn}[Support]
  Let $\psi$, $A$ and $B$ be parametrized formulas, and let $S$ be the
  set of possible substitutions from the set of parametrized variables in $\psi$ ($\Var(\psi)$) into the set of parametrized variables of $(A\Into B)$ ($\Var(A\Into B)$).
%
  We say that $\psi$ supports $(A\Into B)$, whenever
%
  \[ \big( (\bigwedge_{\sigma\in S} \sigma(\psi)\big) \andcond A\big) \Into B \hspace{4em} \text{is valid} \]
%
  We use $\psi\supports(A\Into B)$ as a short notation for
  $\big((\bigwedge_{\sigma\in S} \sigma(\psi)) \andcond A\big) \Into B$.
\end{defn}
Note that if $S'\subseteq S$ is a subset of the substitutions, and
%
  \[ \big( (\bigwedge_{\sigma\in S'} \sigma(\psi)\big) \andcond A\big) \Into B \hspace{4em} \text{is valid} \]
%
then
%
  \[ \big( (\bigwedge_{\sigma\in S} \sigma(\psi)\big) \andcond A\big) \Into B \hspace{4em} \text{is also valid} \]
%
  Essentially, if one succeeds in proving the validity of a formula obtained by removing some of the conjuncts from the antecedent, the validity of the full formula is preserved.
%
  Hence, in practice, it is enough to consider only some of the partial substitutions to show that a support formula is valid.

\begin{itheorem}[Bound an arbitrary number of threads]
	Let $\varphi$ be a thread-parametrized formula, where $\overline{k}=\Var(\varphi)$.
	%
	Let $\tau$ be a transition of $P$ and $\ThetaParam$ the initial condition of $P$.

	To show that $P$ satisfies $\Always\varphi$ (that is, $\varphi$ is an invariant of $P$):
	\hspace{-1em}
	\[
		\begin{array}{r@{\;\;}lr@{\;}@{\;}cl@{\hspace{1em}}l}
			\Premise{S1}. & & \ThetaParam(\overline{k}) &\supports & \varphi & \\

			\Premise{S2}. & \varphi \supports & \tau^{(i)} &\Into& \varphi'  & \text{forall $\tau$ and all $i\in \overline{k}$}\\
			\Premise{S3}. & \varphi\supports & \big(\bigwedge\limits_{x\in\Var(\varphi)} j\neq x \andcond \tau^{(j)} &\Into& \varphi' \big)& \text{forall $\tau$ and one fresh $j\notin\overline{k}$}\\ \hline
			& \multicolumn{4}{c}{\hspace{3em} \Always \varphi} &
		\end{array}
	\]
\label{thm:biggest}
\end{itheorem}

Using this powerful result, we have reduced an arbitrary number of processes sharing the same variables to a finite number of threads sharing the variable.
%
The proof of this result can be found in \citeapos{paperParametrizedInvariants}.
%
We will refer to $\Premise{S1}$ as \concept{initiation} because it depends on the initial condition.
%
$\Premise{S2}$ will be referred as \concept{self-consecution} because it captures the execution of one of the threads mentioned in the formula.
%
Finally, $\Premise{S3}$ will be referred as \concept{others-consecution} because it captures the execution of threads which do not appear in the formula.
%
The example included in appendix \ref{app:exampleFactorial} illustrate the concept of support.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{A Theory of Linked Lists}

\subsection{Description}

In order to work with linked lists in a context with multiple thread using the same list
there are two possible approaches.
%
A thread could lock the entire list, work with the list and then release the lock.
%
There could be some optimizations in this approach, such as a writer-reader system.
%
However, this is extremely unefficient although it could more secure in terms of preventing deadlocks.
%
The other approach is locking and unlocking each node of the list, so multiple threads can work simultaneously using the same list as long as they do not need to use the same node.
%
This approach is called lock-coupling lists.

\begin{defn}[Lock-coupling linked list]
A lock-coupling concurrent list is
a concurrent data type that implements a set by maintaining in the heap an
ordered single-linked list with non-repeating elements.
%
Each node in the list is protected by a lock which guarantees that a
single thread can access the node at the same time.
%
\end{defn}

The way a thread iterates over the list is the following.
%
The thread acquires the lock of the node
that it visits and after that tries to acquire the next node.
The first lock is only released after the lock of the
second node has been successfully acquired.
%
This technique of protecting cells with locks (instead of protecting
the whole data-structure with a single coarse-grain lock) is known as
\concept{fine-grained locking}.

The nodes of a concurrent lock-coupling list are instances of the following
\ListNode class:
%
\[
	  \class \;\Node  \;\left\{
				Elem \:\;\; data; \;
				Addr \:\;\; next; \;
				Lock \:\;\; lock; \;
		\right\}
\]
%
Where the fields are:
\begin{itemize}
		\item \fData: the value stored in the node. This field is also used to keep
			the list ordered.
		\item \fNext: a pointer that stores the address of the next node in
			the list.
		\item \fLock: the lock protecting the node.
\end{itemize}

We assume that the operating system provides the atomic operations \fLock
and \fUnlock.

We will use \concept[Ghost variable]{ghost variables} which are variables that are not present in the program but are added to aid in the verification process.
%
The implementation of concurrent lock-coupling lists has 3 global variables.
%
Two of them are global addresses \head and \tail, and one ghost global variable \region.
%%
The variable \head, an address points to the first node of the list which has the lowest possible value ($-\infty$).
%
The variable \tail, an address points to the last node of the list  which has the lowest possible value ($+\infty$).
%
Finally, the variable \region, a set of addresses, is used to keep track of the portion of the heap whose cells form the list.
%
In Figure \ref{fig:listcode} we present the code of the implementation chosen.

\begin{figure}
	\centering
	\label{fig:listcode}
	\includegraphics[scale=0.4]{listcode}
	\caption{Code of the implementation chosen.}
\end{figure}
%
There are three procedures, \Search, \Insert and \Remove which traverses through the list the way it was explained.

\subsection{TL3}
To prove verification conditions generated in the proof of invariants of lock-coupling lists we need a theory of lists to work with, and axioms in order to prove \gls{FOL} formulas.

\emph{Theory of Linked Lists with Locks}: \TLLpL, is the theory we use for describing linked-list heap memory layouts.
%
\TLLpL is a multi-sorted first-order theory.
%
It is multi-sorted because it has multiple types for its variables (address, element,...).
%
It is a first-order theory because only variables are quantifiable, as in unsorted \gls{FOL}.

In this section we briefly present \TLLpL.
%
A more complete and formal definition of \TLLpL can be found in \citeapos{paperAle} and \citep[6.2]{thesisAle}.

Although some functions are originally defined \citep{thesisAle} in suffix notation (\fNext,\fData and \fLock fields), preffix-notation has been used to describe the theory.
%
The reason for this modification is to be consistent with the syntax of \spass.
%
Furthermore, we use subset of \TLLpL.
%
In the same way \gls{FOL} can be expressed with $\neg,\vee$ but sometimes $\implies$ is included but $\dimplies$ is not,
%
a few functions of \TLLpL have not been used because they can be expressed using others functions in the theory.
%
We proceed to describe the subset of \TLLpL used.

\TLLpL is a composition of theories. The \textbf{sorts} used among this theories are:
%
\cell (representing the nodes of the list),
%
\elem (representing elements),
%
\addr (representing address),
%
\tid (representing thread id),
%
\mem (representing the memory also called heap, represented as maps of \addr to \cell ),
%
\path (representing a finite sequence of address),
%
\sSetTid, \sSetAddr, \sSetElem to represent sets of \tid,\addr or \elem respectively.

For each sort, there is a theory containing its constants, functions and predicates.
%
There is one more theory, $\Sigma_{Bridge}$ is a \emph{bridge theory} containing auxiliary
functions, for example, that allow to map paths of addresses to set of
addresses, or to obtain the set of addresses reachable from a given
address following a chain of \fNext fields.

\subsection{Signature}

We proceed to describe the signature of each theory, listing the sorts used and explaining its functions, predicates and constants.
%
Every theory includes the equality theory \ref{theory:equality}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					TID

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\tid}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\tid}$ : }
%
The sort used is \tid. The “no-thread” value is represented with \fNoThread.
%
Apart from the equality theory, this theory does not have any other predicates or functions.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					ELEM

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\elem}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\elem}$ : }
%
The sort used is \elem.
%
There is a total order which allows to order every set of \elem.
%
In addition, this sort is upper and lower bounded.
%
 The top block contains the functions and the lower block lists the predicates.

\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fHighest & \elem & Maximum value an \elem can take.\\
\fLowest & \elem & Minimum value an \elem can take.\\
\hline\hline
\fLselem & \elem$\times$\elem & Total order relation between \elem.
\\\hline
\end{tabular}
%\caption{\textbf{Signature of $\Sigma_{\ensuremath{\mathit{elem}}}$.} The top block contains the functions and the lower block lists the predicates.}
%\label{table:elem_signature}
\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					CELL

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\cell}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\cell}$ : }
%
The sorts used are \cell,\;\elem,\;\addr,\;\tid.

\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fMkcell & $\elem\times\addr\times\tid \to \cell$ & Constructor\\
\fNext & $\cell \to \addr$ & Getter of \fNext field \\
\fData & $\cell \to \elem$ & Getter of \fData field \\
\fLockID & $\cell \to \tid$ & Getter of \fLockID field \\
\fLock & $\cell\times\tid\to\cell$ & Construct a new \cell with \fData and \fNext \\
&&\;\;\;								values of the given \cell, \\
&&\;\;\;				using the \tid for the \fLockID field.\\
\fError & $\cell$ & Constant value used to model \\
&&\;\;\;				incorrect memory deference.
\\\hline
\end{tabular}
%\caption{\textbf{Functions of $\Sigma_{\cell}$} theory.}
%\label{table:cell_signature}
\end{center}

The function \fUnlock could be considered. Actually, \cite{thesisAle} includes it in the theory but it has not been included in this work.
%
The reason is justified because to \fUnlock a \cell is equivalent to \fLock a \cell with \fNoThread value.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					MEMORY

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\mem}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\mem}$ : }
%
The sorts used are \mem,\cell and \addr.

\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fNull & $\addr$ & Null address \\
\fRd & $\mem\times\addr\to\cell$ & Models memory deference. \\
&&								\;\;\; Returns the value from the \mem the \cell \\
&&								\;\;\; stored in the \addr.\\
\fUpd & $\mem\times\addr\times\cell\to\mem$ & Creates a new \mem from the given one
\\\hline
\end{tabular}
%\caption{\textbf{Functions of $\Sigma_{\mem}$} theory}
\label{table:memory_signature}
\end{center}

A function related with \mem theory is \fMalloc, used in the \insertprg procedure.
%
The function \fMalloc does not belongs to \gls{SPL} or \TLLpL but it can be translated as a conjunction of assignments and assignments are allowed in both theories.
%
The function \fMalloc returns a new fresh address different to every other address in use, so the \freshaddr returned by \fMalloc is not equal to \head, nor \tail, etc.
%
\fMalloc formal representation correspond to a big conjunction of all the formulas stating \freshaddr is not equal to \addr, for all \addr appearing in the formula (except itself).
%\[\forall x,y. [x\neq y \andcond x=\fMalloc(h) \implies h(x)\neq h(y)]\]

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					SETADDR

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\sSetAddr}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\sSetAddr}$ : }
%
It models the usual set theory.
%
We preferred a prefix version of each function and predicate to be consistent with Section \ref{ax::fulllist}.
%

The intersection function and the subset predicate have not been included, even tough \citep{thesisAle} uses them.
%
They were not used because they were redundant.

\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fEmptyset & \sSetAddr & Empty set\\
\fSingl & $\addr\to\sSetAddr $& Constructor of a single-element set.\\
\fUnion & $\sSetAddr\times\sSetAddr\to\sSetAddr$&\\
\fSetdiff & $\sSetAddr\times\sSetAddr\to\sSetAddr$&\\
\hline\hline
\pIn & $\sAddr\times\sSetAddr $&
\\\hline
\end{tabular}
%\caption{\textbf{Signature of $\Sigma_{\sSetAddr}$.} The top block contains the functions and the lower block lists the predicates.}
\label{table:setaddr_signature}
\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					SETELEM

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\sSetElem}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\sSetElem}$ : }
%
Again, it models the usual set theory.
%
The signature is described in Table \ref{table:setelem_signature}.

\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fEmptysetElem & $\sSet $& Empty set\\
\fSinglElem & $\elem\to\sSet $& Constructor of a single-element set.\\
\fUnionElem & $\sSet\times\sSet\to\sSet$&\\
\fSetdiffElem & $\sSet\times\sSet\to\sSet$&\\
\hline\hline
\pInElem & $\sAddr\times\sSet $&
\\\hline
\end{tabular}
%\caption{\textbf{Signature of $\Sigma_{\sSetElem}$.} The top block contains the functions and the lower block lists the predicates.}
\label{table:setelem_signature}
\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					SETTID

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{\sSetTid}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{\sSetTid}$ : }
%
The signature is described in Table \ref{table:settid_signature}.

\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fEmptysetTid & $\sSetAddr $& Empty set\\
\fSinglTid & $\addr\to\sSetAddr $& Constructor of a single-element set.\\
\fUnionTid & $\sSetAddr\times\sSetAddr\to\sSetAddr$&\\
\fSetdiffTid & $\sSetAddr\times\sSetAddr\to\sSetAddr$&\\
\hline\hline
\pInTid & $\sAddr\times\sSetAddr$ &
\\\hline
\end{tabular}
%\caption{\textbf{Signature of $\Sigma_{\sSetAddr}$.} The top block contains the functions and the lower block lists the predicates.}
\label{table:settid_signature}
\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%					BRIDGE

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%\begin{center}\rule{4cm}{0.4pt} $\Sigma_{Bridge}$ \rule{4cm}{0.4pt}\end{center}
\paragraph{$\Sigma_{Bridge}$ : }
%
This theory is much more extensive in \cite{thesisAle}.
%
However, aiming for simplicity, we do not include every function and predicate because we do not use them in our proofs.
%
The only function used in the proofs is:
\begin{center}
\begin{tabular}{|rrl|}
  \hline
\fAddrToSet & $\mem\times\addr\to\sSetAddr $& Returns the set of \addr reachable from the \addr given.\\
\hline
\end{tabular}
%\caption{\textbf{Signature of $\Sigma_{\sSetAddr}$.}}
\label{table:bridge_signature}
\end{center}